Rails联系表单`undefined method`

时间:2014-11-13 14:37:01

标签: ruby-on-rails contact-form

我正在尝试在Rails中构建联系表单而不将邮件存储在我的数据库中。但是当我发送表单时,我收到undefined method 'name' for nil:NilClass错误。

我的MessagesController

def create
  @message = Message.new(message_params)
  if @message.valid?
    # TODO send message here
    Messages.new_messages_email(@mailer).deliver
    redirect_to root_url, notice: "Message sent! Thank you for contacting us."
  else
    redirect_to root_url, notice: "Something went wrong, try again!"
  end
end

private
def message_params
  params.require(:message).permit(
    :name, 
    :message,
    :email
  )
end

我的消息模型

class Message
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name, :email, :message

  validates_presence_of :name
  validates :email, :email_format => {:message => 'is not looking good'}
  validates_length_of :message, :maximum => 500

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end
end

电子邮件正文

!!!
%html
  %body
    %p
      = @mailer.name
      Schreef het volgende:
    %p= @mailer.message
    %p= @mailer.email

在我的路线中我有

  resources :messages

我忘了发布我的消息邮件

class Messages < ActionMailer::Base
  default from: "info@domein.nl"

    def new_messages_email(mailer)

    @mailer = mailer
    mail(to: 'peter@no-illusions.nl',
        subject: 'Iemand wilt contact met U')
    end
end

完成我的表格,

= form_for @message do |f|
  .field
    %br/
    = f.text_field :name, :placeholder => "Naam"
  .field
    %br/
    = f.text_field :email, :placeholder => "Emailadres"
  .field
    %br/
    = f.text_area :message, :rows => 5, :placeholder => "Uw bericht"
  .actions= f.submit "Verstuur bericht", :id => "submit"

在我的MessagesController中,我定义了create函数的参数,但是我做错了,遗忘或忽略导致错误。

1 个答案:

答案 0 :(得分:2)

在您的控制器中应该是:

Messages.new_messages_email(@message).deliver # not @mailer

除此之外,您必须在邮件中重新初始化@message,例如:

class Messages < ActionMailer::Base

  def new_messages_email(msg)
    @message = msg
  end

end