2014-09-15 2 views
1

Я проработал довольно старое учебное пособие, чтобы создать контактную форму, а затем создать почтовую программу, которая отправляется администратору сайта. Я сталкиваюсь с некоторыми проблемами, я думаю, потому что я на рельсах 4.1.1, и учебник настолько стар! Мне было интересно, может ли кто-нибудь дать мне какое-то руководство - я изучаю рельсы. Ошибка я в настоящее время получаю NoMethodError в MessagesController # создать неопределенный метод `объект» для # объекта message.subjectaction mailer for rails 4

вот мой код

сообщений контроллера:

class MessagesController < ApplicationController 
    before_action :set_message, only: [:show, :edit, :update, :destroy] 

    # GET /messages 
    # GET /messages.json 
    def index 
    @messages = Message.all 
    end 

    # GET /messages/1 
    # GET /messages/1.json 
    def show 
    end 

    # GET /messages/new 
    def new 
    @message = Message.new 
    end 

    # GET /messages/1/edit 
    def edit 
    end 

    # POST /messages 
    # POST /messages.json 
    def create 
    @message = Message.new(message_params) 

respond_to do |format| 
    if @message.save 
    ContactMailer.deliver_message(@message) 
    flash.now[:notice] = 'Thank you for your message!' 
    format.html { redirect_to root_path } 
    format.json { render :show, status: :created, location: @message } 
    else 
    format.html { render :new } 
    format.json { render json: @message.errors, status: :unprocessable_entity } 
    end 
end 

конец

# PATCH/PUT/messages/1 # PATCH/PUT /messages/1.json def update reply_to do | формат | if @ message.update (message_params) format.html {redirect_to @message, notice: 'Сообщение успешно обновлено.' } format.json {визуализации: шоу, статус:: хорошо, местоположение: @message} еще format.html {визуализации: редактировать} format.json {визуализации JSON: @ message.errors статус:: unprocessable_entity} конец конца конца

# УДАЛИТЬ/сообщения/1 # УДАЛИТЬ /messages/1.json защиту уничтожить @ message.destroy respond_to делать | формат | format.html {redirect_to messages_url, note: 'Сообщение успешно уничтожено.' } format.json {голова: no_content} конец конец

частный # Используйте обратные вызовы имеют общие настройки или ограничения между действиями. Защиту set_message @message = Message.find (Params [: ID]) конец

# Never trust parameters from the scary internet, only allow the white list through. 
def message_params 
    params.require(:message).permit(:name, :email, :company, :phone, :subject, :body) 
end 

конец

development.rb:

Rails.application.configure do 
    # Settings specified here will take precedence over those in config/application.rb. 

    # In the development environment your application's code is reloaded on 
    # every request. This slows down response time but is perfect for development 
    # since you don't have to restart the web server when you make code changes. 
    config.cache_classes = false 

    # Do not eager load code on boot. 
    config.eager_load = false 

    # Show full error reports and disable caching. 
    config.consider_all_requests_local  = true 
    config.action_controller.perform_caching = false 

    # Don't care if the mailer can't send. 
    config.action_mailer.raise_delivery_errors = true 

    config.action_mailer.delivery_method = :smtp 
    config.action_mailer.smtp_settings = { 
    address: "smpt.gmail.com", 
    port: "587", 
    domain: "gmail.com", 
    authentication: "plain", 
    enable_starttls_auto: true, 
    user_name: 'your_email_username', 
    password: 'your_email_password' 
    } 

    CONTACT_RECIPIENT = '[email protected]' 
    # Print deprecation notices to the Rails logger. 
    config.active_support.deprecation = :log 

    # Raise an error on page load if there are pending migrations. 
    config.active_record.migration_error = :page_load 

    # Debug mode disables concatenation and preprocessing of assets. 
    # This option may cause significant delays in view rendering with a large 
    # number of complex assets. 
    config.assets.debug = true 

    # Adds additional error checking when serving assets at runtime. 
    # Checks for improperly declared sprockets dependencies. 
    # Raises helpful error messages. 
    config.assets.raise_runtime_errors = true 

    # Raises error for missing translations 
    # config.action_view.raise_on_missing_translations = true 

    # Required for Devise gem 
    config.action_mailer.default_url_options = { :host => 'localhost:3000' } 

end 

class ContactMailer < ActionMailer::Base 
    default from: "[email protected]" 

    # Subject can be set in your I18n file at config/locales/en.yml 
    # with the following lookup: 
    # 
    # en.contact_mailer.message.subject 
    # 

    def message(message) 
    subject message.subject 
    body  :message => message 
    recipients CONTACT_RECIPIENT 
    from  message.email 
    sent_on Time.now 
    end 

    end 
end 

message.html.erb

Email from your web site 

From: <%= @message.name %> 

Company: <%= @message.company %> 

Phone: <%= @message.phone %> 

Message: <%= @message.body %> 

сообщения/_form.html.erb

<%= semantic_form_for @message do |f| %> 
    <%= f.inputs do %> 
    <%= f.input :name %> 
    <%= f.input :company %> 
    <%= f.input :phone %> 
    <%= f.input :email %> 
    <%= f.input :subject %> 
    <%= f.input :body %> 
    <% end %> 

    <%= f.actions do %> 
    <%= f.action :submit, :as => :input %> 
    <% end %> 
<% end %> 

соответствующая часть файла схемы БД

create_table "messages", force: true do |t| 
    t.string "name" 
    t.string "company" 
    t.string "phone" 
    t.string "email" 
    t.string "subject" 
    t.text  "body" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 
+0

ли вы кладете класс 'ContactMailer' внутри' development.rb'? Возможно, вы также поймете [Основы ActionMailer] (http://guides.rubyonrails.org/action_mailer_basics.html). –

+0

Подходит ли столбец в таблице сообщений? вы можете дважды проверить свой db/schema.rb, чтобы убедиться, что он указан в таблице сообщений. Кроме того, что сказал Джастин.ваш ContactMailer должен быть в приложении/почтовом отправлении, а не в development.rb – johndavid400

+0

Я считаю, что в столбце темы есть - я отредактировал вопрос соответственно! – Lilp

ответ

1
def deliver_message(message) 
    subject message.subject 
    body  :message => message 
    recipients CONTACT_RECIPIENT 
    from  message.email 
    sent_on Time.now 
end 

должен быть

def deliver_message(message) 
    @message = message 
    mail(subject: message.subject, body: message.body, recipients: CONTACT_RECIPIENT, from: message.email, sent_on: Time.now) 
end 
+0

это меняет тонны ошибок ... – Lilp

+0

SyntaxError (/Users/em/new/app/mailers/contact_mailer.rb:26: синтаксическая ошибка, неожиданное ':', ожидающее ключевое слово_ид subject: message.subject ^ /Users/em/new/app/mailers/contact_mailer.rb:27: синтаксическая ошибка, неожиданный ':', ожидающий keyword_end body:: message => message ^ /Пользователи/em/new/app/mailers/contact_mailer.rb: 28: синтаксическая ошибка, неожиданные ':', ожидающие keyword_end получатели: CONTACT_RECIPIENT ^ /Users/em/new/app/mailers/contact_mailer.rb:29: синтаксическая ошибка, неожиданное ':', ожидающее ключевое слово_end от: сообщение.email ^ – Lilp

+0

/Users/em/new/app/mailers/contact_mailer.rb:30: синтаксическая ошибка, неожиданный ':', ожидающий keyword_end sent_on: Time.now ^ /Пользователи/em/new/app/mailers/contact_mailer. rb: 34: синтаксическая ошибка, неожиданное keyword_end, ожидающая окончания ввода): – Lilp

Смежные вопросы