我正在将电子邮件保存到数据库然后发送。我正在使用电子邮件模型来验证输入,但我不确定如何显示错误消息。我得到一个未定义的方法`错误' for nil:fullmessage.errors.any的NilClass错误?索引操作中的行(下面突出显示)
查看
<%= form_tag("/thank_you") do %>
<% if @fullmessage.errors.any? %> # <----- This line
<h3>Errors</h3>
<ul>
<% @fullmessage.errors.full_messages.each do |message| %> # Would also cause an error if exemption not already raised
<li><%= message %></li>
<% end %>
</ul>
<% end %>
<div class="row">
<div class="col-md-5">
<div class="form-group">
<%= text_field_tag :first_name, nil, class: 'form-control', placeholder: 'First Name' %>
</div>
</div>
<div class="col-md-7">
<div class="form-group">
<%= text_field_tag :last_name, nil, class: 'form-control', placeholder: 'Last Name' %>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<%= text_field_tag :email, nil, class: 'form-control', placeholder: 'Email Address' %>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group text-area-wide">
<%= text_area_tag :message, nil, class: 'form-control text-area-wide', placeholder: 'When are you available?' %>
</div>
</div>
</div>
<%= submit_tag 'Get Started', class: 'btn btn-success' %>
<p><a href="http://www.skype.com/en/" target="_blank">Skype</a> required</p>
<% end %>
控制器
def thank_you
@first_name = params[:first_name]
@last_name = params[:last_name]
@email = params[:email]
@message = params[:message] || "Hello!"
@fullmessage = Email.create(first_name: @first_name, last_name: @last_name, email: @email, message: @message)
if @fullmessage.valid?
ActionMailer::Base.mail(
:from => @email,
:to => 'erikvdw@comcast.net',
:subject => "A new contact form message from #{@first_name} #{@last_name}",
:body => @message).deliver
else
redirect_to root_path
flash[:alert] = 'There was an issue with your submission'
end
end
模型
class Email < ActiveRecord::Base
validates_length_of :first_name, :maximum => 25, :minimum => 2
validates_length_of :first_name, :maximum => 30, :minimum => 2
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
validates_length_of :message, :maximum => 500, :minimum => 20
end
答案 0 :(得分:0)
Nil类意味着@fullmessage是nil并且尚未设置,并且nil没有方法错误,因此错误。
当您重定向时,@ fulllmessage值将没有任何内容,因为http是无状态的。如果没有缓存和cookie,每个请求都会重新创建每个变量。认为你要做的是显示flash消息,如果是这种情况你可以将@ fullmessage.errors添加到flash并能够在重定向上显示它。
答案 1 :(得分:0)
您有两种选择:
render
代替重定向(这样您就可以保留@fullmessage
个对象。flash[:alert]
并在视图中显示第二个选项更通用,您可以将相关代码添加到布局中并在整个站点中使用它。 E.g:
<% if !flash.empty? %>
<div id="flash">
<% flash.keys.each do |k| %>
<div class="alert alert-<%= k %>">
<%= flash[k] %>
</div>
<% end %>
</div>
<% end %>