【问题标题】:Passing dynamic subject to Rails mail_form将动态主题传递给 Rails mail_form
【发布时间】:2015-07-25 20:21:19
【问题描述】:

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

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

在控制器中

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">

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 mail-form


    【解决方案1】:

    代替:

    = hidden_field_tag :mail_subject, @the_subject
    

    你会想要使用:

    = f.hidden_field :mail_subject, value: @the_subject
    

    如果您检查登录到您的development.log 的参数,您就会明白原因。

    当您使用hidden_field_tag 时,mail_subject 被定义为它自己的独立参数,不会包含在contact 哈希中。你会有类似的东西:

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

    但是当您使用 f.hidden_field 时,mail_subject 将包含在 contact 哈希中。你会有类似的东西:

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

    然后当您调用Contact.new(params[:contact]) 时,新的联系人对象将获得mail_subject 值。

    【讨论】:

    • 杜德!知识无价!我尝试了很多东西,包括使用 value:@the_subject 和使用 f.hidden_​​field,但出于某种原因,我从未同时尝试过它们。它现在完美无缺。我应该在花 2 个小时弄清楚这一点之前问清楚。
    • 酷。然后,如果您想删除@the_subject 变量的使用,您应该能够让您的where_to_buy 操作执行@contact = Contact.new(mail_subject: "Where to buy"),而视图可以只使用= f.hidden_field :mail_subject
    • 太棒了。现在我想起来,这很有意义。再次感谢!
    • 对了,你对这个有什么意见吗?:stackoverflow.com/questions/31618138/…
    猜你喜欢
    • 2012-07-14
    • 2018-03-06
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多