我尝试从包含三个参数的表单中验证并保存电子邮件:name,:email和:message,然后发送整个电子邮件。目前,电子邮件将成功发送,无需验证参数或创建电子邮件实例。
控制器
def thank_you
@name = params[:name]
@email = params[:email]
@message = params[:message] || "Hello!"
if Email.create(name: @name, email: @email, message: @message)
ActionMailer::Base.mail(
:from => @email,
:to => 'erikvdw@comcast.net',
:subject => "A new contact form message from #{@name}",
:body => @message).deliver
end
end
模型
class Email < ActiveRecord::Base
validates_presence_of :name
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
validates_length_of :message, :maximum => 500, :minimum => 10
end
查看
<%= form_tag("/thank_you") do %>
<div class="row">
<div class="col-md-5">
<div class="input-group">
<%= text_field_tag :name, nil, class: 'form-control', placeholder: 'Your Name' %>
</div>
</div>
<div class="col-md-7">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">@</span>
<%= text_field_tag :email, nil, class: 'form-control', placeholder: 'Your Email Address' %>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<div class="input-group text-area-wide">
<%= text_area_tag :message, nil, class: 'form-control text-area-wide', placeholder: 'When are you available?' %>
</div>
</div>
</div>
<br>
<%= submit_tag 'Get Started', class: 'btn btn-success' %>
<p><a href="http://www.skype.com/en/" target="_blank">Skype</a> required</p>
<% end %>
答案 0 :(得分:0)
我认为你在操作中的问题
Email.create
&#13;
因为它在内存中创建了一个实例而没有将实例保存到数据库中。 您必须直接调用save方法或检查验证方法 - email.valid?,如下所示:
email = Email.create(name: @name, email: @email, message: @message)
if email.valid?
#send email
end
&#13;