【问题标题】:rails 4 show error message validations in viewsrails 4 在视图中显示错误消息验证
【发布时间】:2013-10-03 15:19:34
【问题描述】:

嗨,我有嵌套资源:

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

【问题讨论】:

  • @msg.errors 有什么东西吗?当您尝试保存时,@msg 中的数据实际上是什么样的?您提到它正在执行 ROLLBACK,但如果验证确实失败,它根本不会尝试执行 INSERT。请参阅edgeguides.rubyonrails.org/… - 第 1.2 节,第二段。这表明可能验证实际上并没有失败,并且保存时出现了其他问题(导致 ROLLBACK)。
  • 您的Posts 模型是否有accepts_nested_attributes_for :msg?如果是这样,我想知道错误是否会出现在@post.errors 中。也许试试看。
  • 我试图消除 msg 模型中的验证,并且在数据库中提交了空白注释。在验证活动的情况下,空白注释不会被提交,而是被回滚。我在服务器的日志和数据库查询中看到了这一点。

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


【解决方案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 %>

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 是的,根据这篇文章archives.ryandaigle.com/articles/2009/8/10/…,如果表单有错误,respond_with 方法会以新的方式响应。所以我为 msg 创建了一个新视图,现在表单重定向到这里(如果有错误),否则表单重定向到 post 资源的显示。
    • 在您的问题中,表单出现在show 视图中,而不是推荐的new 中。如果您查看文章,您会发现create 具有ifelse 条件。 else(如果未保存)必须 RENDER 表单,然后 @msg.errors.any? 将变为 true 并显示错误。如果您在未保存时使用 REDIRECT,您将不会拥有 @msg.errors....
    • 好的,谢谢,现在我已经完全理解了这种行为。我的问题是我应该重定向错误,而不是在 :new 中,而是在 show..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 2022-06-20
    • 2017-10-19
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多