2013-10-03 47 views
2

您好我有嵌套资源:导轨4示出在视图中的错误消息验证

resources :posts do 
    resources :msgs 
end 

和一些验证:

class Msg < ActiveRecord::Base 
    belongs_to :post 
    validates :body ,presence:true 
end 

控制器:

# msgs_controller.erb 
def create 
@post = Post.find(params[:post_id]) 
@[email protected](msg_params) 
@msg.user=current_user 
@msg.email=current_user.email 
@msg.autor=current_user.name 

if @msg.save 
    flash[:notice] = t '.create' 
end 
respond_with(@post,@msg) 
end 

和一个视图: EDIIT:/views/posts/show.html.rb #/views/show.html.erb

<h2>Add a comment:</h2> 
<%= form_for([@post, @post.msgs.build]) do |f| %> 

    <% if @msg.errors.any? %> 
     <div id="error_explanation"> 

      <h2><%= pluralize(@msg.errors.count, "error") %> prohibited this msg from being saved:</h2> 

      <ul> 
      <% @msg.errors.full_messages.each do |msg| %> 
       <li><%= msg %></li> 
      <% end %> 
      </ul> 
     </div> 
    <% end %> 


    <p> 
     <%= f.label :body %><br /> 
     <%= f.text_area :body %> 
    </p> 
    <p> 
     <%= f.submit %> 
    </p> 
<% end %> 

当body字段为空时,应用程序不显示错误消息,但验证结果正常,因为服务器显示ROLLBACK而不是COMMIT。问题是在视图中显示错误消息,你能帮助我吗?

+0

有什么都在'@ msg.errors'?在你试图保存的时候,@ msg'中的数据实际上是什么样的?你提到它正在做一个ROLLBACK,但如果验证确实失败了,它根本不会尝试执行INSERT。请参阅http://edgeguides.rubyonrails.org/active_record_validations.html#presence - 第1.2节第二段。这表明验证可能并不真正失败,并且保存中的其他内容出错(导致ROLLBACK)。 –

+0

您的'Posts'模型是否有'accep_nested_attributes_for:msg'?如果是这样,我想知道这些错误是否会出现在@ post.errors中。也许试试看吧。 – lurker

+0

我已尝试消除msg模型中的验证,并在db中提交blanck注释。验证激活时,blanck注释不会被提交,但会被回滚。我已经在服务器的日志和数据库查询中看到了这一点。 – user1066183

回答

0

该表格应该在new而不是在show视图中。然后,您可以渲染页面,如果不保存显示错误。

.... 
if @msg.save 
    flash[:notice] = t '.create' 
else 
    render 'new' 
end 
.... 
+0

是根据这篇文章http://archives.ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering respond_with方法响应与新的如果窗体有错误。所以我为msg创建了一个新视图,现在表单在这里重定向(如果有错误),否则表单将重定向到post资源的显示。 – user1066183

+0

在你的问题中,窗体出现在'show'视图中,而不是按照推荐的'new'。如果你看看这篇文章,你会发现'create'有一个'if'和'else'的条件。 'else'(如果没有保存)必须渲染表单,然后'@ msg.errors.any?'将会是'true',并显示错误。如果你没有保存时​​使用REDIRECT,你将不会有'@ msg.errors' .... – gabrielhilal

+0

好的谢谢,现在我已经完全理解了这个行为。我的问题是我应该重定向错误不在:新,但在节目中.. – user1066183

1

退房这篇文章怎么办提示信息钢轨4路:http://blog.remarkablelabs.com/2012/12/register-your-own-flash-types-rails-4-countdown-to-2013

从文章:

# app/controllers/application_controller.rb 
class ApplicationController 
    ... 
    add_flash_types :error, :another_custom_type 
end 

# app/controllers/users_controller.rb 
class UsersController < ApplicationController 
    def create 
    ... 
    redirect_to home_path, 
     error: "An error message for the user" 
    end 
end 

# app/views/home/index 
<%= error %>