0

我正在使用 gem mail_form 来处理 Rails 应用程序中的联系,我有 6 种不同的联系表格。

我在表单中放置了一个 hidden_​​field_tag 并将所需的主题作为变量传递。在 html 中,值在那里,但电子邮件到达时 (no subject)。我做错了什么?

在控制器中

def where_to_buy
   @contact = Contact.new
   @the_subject = "Where to buy"
end

联系方式

= form_for @contact do |f|
  = render "form", f: f
  = f.text_area :message
  .hide
    = f.text_field :nickname, hint: 'Leave this field empty!'
    = hidden_field_tag    :mail_subject, @the_subject
  = f.submit "Send Message"

在模型中

class Contact < MailForm::Base
  attribute :mail_subject
  attribute :first_name, validate: true
  attribute :last_name,  validate: true
  attribute :message,    validate: true
  attribute :nickname,   captcha:  true

  def headers
    {
      subject: %(#{mail_subject}),
      to:      "jorge@email123.com",
      from:    %("#{first_name} #{last_name}" <#{email}>)
    }
  end
end

在chrome中输出html:

<input type="hidden" name="mail_subject" id="mail_subject" value="Where to buy">
4

1 回答 1

1

Instead of:

= hidden_field_tag :mail_subject, @the_subject

You will want to use:

= f.hidden_field :mail_subject, value: @the_subject

If you inspect the parameters that are logged into your development.log you will see why.

When you use hidden_field_tag the mail_subject is defined as its own independent parameter and will not be included in the contact hash. You'll have something like:

params = { "contact" => { "message" => "text here", ... }, "mail_subject => "Where to buy" }

But when you use f.hidden_field the mail_subject will be included in the contact hash. You'll have something like:

params = { "contact" => { "message" => "text here", "mail_subject => "Where to buy", ... } }

And then when you call Contact.new(params[:contact]) the new contact object will get the mail_subject value.

于 2015-07-25T22:41:49.120 回答