rails 4在视图中显示错误消息验证

时间:2013-10-03 15:19:34

标签: ruby-on-rails validation form-for

您好我有嵌套资源:

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])
 @msg=@post.msgs.build(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 %>

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

2 个答案:

答案 0 :(得分:1)

查看本文,了解如何使用Rails 4方式执行Flash消息: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 %>

答案 1 :(得分:0)

表单应位于new而不是show视图中。然后,如果未保存则可以渲染页面以显示错误。

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