发送电子邮件时,MailForm不包含表单中的字段

时间:2016-09-14 10:37:46

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

我正在尝试设置MailForm以在我的Rails 4应用中发送电子邮件,除了一件事,我实际上让它工作。

由于某种原因,它不包含电子邮件中的message字段(该表单只包含nameemailmessage字段,以及隐藏的nickname } field。。

以下是我的Contact模型的样子:

class Contact < MailForm::Base
  attribute :name,     validate: true
  attribute :email,    validate: /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  attribute :message
  attribute :nickname, captcha: true

  append :remote_ip, :user_agent

  def headers
    {
      subject: 'Question',
      to: ENV['ACTION_MAILER_USERNAME'],
      from: %("#{name}" <#{email}>)
    }
  end
end

如果我将validate: true添加到attribute :message,验证将无法正常工作,即即使不是,也会说该字段为空,因此如果我打开{{1的验证属性,我甚至无法提交表单。

在MailForm文档示例中,:message字段没有验证,但是当我提交表单时,发送给我的邮件只包含:message:name字段,没有{{ 1}}。

我的:email看起来像这样:

:message

这是我的html表单:

ContactsController.rb

所以,基本上,我按照MailForm文档中的示例进行操作,但仍然无法使其正常工作。

你能帮我找出我做错的事吗?

更新1

似乎问题在于params。以下是提交表单时class ContactsController < ApplicationController def new @contact = Contact.new end def create @contact = Contact.new(contact_params) @contact.request = request if @contact.deliver flash.now[:notice] = I18n.t('contact.message_success') redirect_to root_path else flash.now[:error] = I18n.t('contact.message_error') render :new end end private def contact_params params.require(:contact).permit(:name, :email, :message) end end 哈希的样子:

   <%= simple_form_for @contact do |f| %>
       <%= f.input :name, required: true, label: false %>
       <%= f.input :email, required: true, label: false %>
       <%= f.input :message, as: :text, required: true, label: false %>
       <div class="hidden">
           <%= f.input :nickname, hint: 'Leave this field blank!' %>
       </div>
       <%= f.button :submit, t('contact.action') %>
   <% end %>

1 个答案:

答案 0 :(得分:0)

好的,这就是我如何运作:

因为params哈希看起来像这样:

{"utf8"=>"✓", "authenticity_token"=>"kOtHaOTBNvl5KpPBLB31LtQ6W0jUoohg012ZbQ5qyg0fAGW6y5mMR5FSAEcY4kyotFYihTvRSvTtbDsc8oMQ3g==", "contact"=>{"name"=>"Testing", "email"=>"whatever@test.com", "nickname"=>""}, "Message"=>"Hello everyone!", "commit"=>"Send", "locale"=>"en"}

我无法获取消息字段,因为当我执行params.require(:contact)时,它只返回了我这样的哈希:{"name"=>"Testing", "email"=>"whatever@test.com", "nickname"=>""},并且消息字段不在:contact内。

所以我必须将contact_params方法更改为:

  def contact_params
    params.require(:contact).permit(:name, :email)
                            .merge(message: params.fetch('Message'))
  end

现在它返回我需要的内容,即像这样的哈希:

{"name"=>"Testing", "email"=>"whatever@test.com", "message"=>"Hello everyone!"}

希望它有所帮助!

相关问题