【发布时间】:2016-09-14 10:37:46
【问题描述】:
我正在尝试设置 MailForm 以在我的 Rails 4 应用程序中发送电子邮件,除了一件事之外,我实际上让它工作了。
由于某种原因,它不包括电子邮件中的message 字段(该表单只有name、email 和message 字段,外加一个隐藏的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 hash 的样子:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"kOtHaOTBNvl5KpPBLB31LtQ6W0jUoohg012ZbQ5qyg0fAGW6y5mMR5FSAEcY4kyotFYihTvRSvTtbDsc8oMQ3g==", "contact"=>{"name"=>"Testing", "email"=>"whatever@test.com", "nickname"=>""}, "Message"=>"Hello everyone!", "commit"=>"Send", "locale"=>"en"}
【问题讨论】:
标签: ruby-on-rails validation email ruby-on-rails-4 mail-form