嵌套表单验证在Rails应用程序中不起作用 [英] Nested form validations not working in rails app

查看:78
本文介绍了嵌套表单验证在Rails应用程序中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的验证不适用于嵌套表单-消息,该消息在其他模型的显示页面中.

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

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

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

_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?

谢谢!

推荐答案

我认为您的控制器存在问题:

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.

这篇关于嵌套表单验证在Rails应用程序中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆