Nested form validations not working in rails app

五迷三道 提交于 2019-12-25 04:43:11

问题


My validations are not working for a nested form - messages, which is in other models show page.

Here's the code:

Reserve Online:

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

an the 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 %>

The whole code above works fine, but the validation part is simply ignored. And I don't see any errors. So I Can't figure out what I'm doing wrong. Can You help?

Thank you!


回答1:


I think there is a problem in your controller:

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

Try to fix that and see if it helps.



来源:https://stackoverflow.com/questions/12041011/nested-form-validations-not-working-in-rails-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!