0

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

由于某种原因,它不包括message电子邮件中的字段(表单只有name,emailmessage字段,加上一个隐藏nickname字段)。

这是我的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正常工作,即即使不是,它也会说该字段为空,所以如果我打开:message属性的验证,我什至无法提交表单。

在 MailForm 文档示例中,没有对:message字段进行验证,但是当我提交表单时,发送给我的消息仅包含:name:email字段,没有:message

我的ContactsController.rb样子是这样的:

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

这是我的 html 表单:

   <%= 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 %>

因此,基本上,我遵循了 MailForm 文档中的示例,但仍然无法使其正常工作。

你能帮我找出我做错了什么吗?

更新 1

似乎问题出在参数上。以下是params提交表单时哈希的样子:

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

1 回答 1

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

希望它可以帮助某人!

于 2016-09-14T10:59:00.117 回答