我的验证不适用于嵌套表单 - 消息,在其他模型中显示页面。
这是代码:
在线预约:
<%= form_for([@trip, @trip.messages.build]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_field :name, :class => "span3", :placeholder => "Name:" %>
<%= f.text_field :email, :class => "span3", :placeholder => "Email:" %>
<div class="h">
<%= f.text_field :subject, :class => "h", :value => (@trip.title) %>
</div>
<%= f.text_area :body, :class => "input-xlarge3", :placeholder => "Message:", :id => "textarea", :rows => "3" %>
<%= f.submit :class => " btn btn-primary btn-large ", :value => "Send Message" %>
<% end %>
</div>
Message.rb
class Message < ActiveRecord::Base
belongs_to :trip
attr_accessible :name, :email, :subject, :body
validates_presence_of :name
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
validates_length_of :body, :maximum => 500
end
一个messages_controller.rb
class MessagesController < ApplicationController
def create
@trip = Trip.find(params[:trip_id])
@message = @trip.messages.create(params[:message])
if @trip.messages.create
MessageMailer.send_message(@message).deliver
redirect_to thank_you_path
else
redirect_to trip_path(@trip)
end
end
end
_error_messages.rb
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-error">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li>* <%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
上面的整个代码工作正常,但验证部分被忽略了。我没有看到任何错误。 所以我无法弄清楚我做错了什么。你能帮忙吗?
谢谢!
答案 0 :(得分:0)
我认为您的控制器存在问题:
def create
@trip = Trip.find(params[:trip_id])
@message = @trip.messages.create(params[:message])
# the following line doesnt make sense
# you're recreating an empty message
# it should be something like "if @message.valid?"
if @trip.messages.create
MessageMailer.send_message(@message).deliver
redirect_to thank_you_path
else
redirect_to trip_path(@trip)
end
end
尝试解决这个问题,看看是否有帮助。