2

嗨,我有嵌套资源:

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

和一个视图:编辑:/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。问题是在视图中显示错误消息,你能帮我吗?

4

2 回答 2

1

查看这篇关于如何使用 Rails 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 %>
于 2014-01-07T03:43:14.760 回答
0

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

....
 if @msg.save
   flash[:notice] = t '.create'
 else
   render 'new'
 end
....
于 2013-10-04T01:30:59.673 回答