【问题标题】:How to handle error messages in polymorphic associations for rails?如何处理rails的多态关联中的错误消息?
【发布时间】:2017-07-05 19:39:13
【问题描述】:

我一直在这个网站上关注多态关联教程https://www.richonrails.com/articles/polymorphic-associations-in-rails

很遗憾,作者没有提供教程的后半部分。

我想知道处理错误消息的正确语法是什么。

在interactions/new.html.erb中,

<%= form_form [@context, @interaction] do |f| %>
  <% render 'shared/errors', object: f.object%>

在shared/_errors.html.erb中,

<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(object.errors.count, "error") %>.
    </div>
    <ul>
     <% object.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
     <% end %>
    </ul>
 </div>
<% end %>

当用户尝试错误地输入新的交互时,说超出字数限制,它应该告诉用户。但是,什么都不会发生。

如果不是多态关联就容易了, 会起作用。

我试过了 它没有用。

有什么线索吗?提前致谢! (红宝石 2.3.3,轨道 5.0.1)

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations


    【解决方案1】:

    今天才发现!可能不能最好地解释这一点,但问题是当发生错误并且重新呈现表单时,错误会保存到您调用保存的对象(@interaction)(@interaction.save)。它创建了这个错误对象 ActiveModel::Errors:0x007f62d4221698。如果你在 create 方法中“logger.debug @interaction.errors.full_messages”,你可以看到错误信息

    if @interaction.save
      redirect_to context_url(context), notice: "The interaction has been successfully created."
    else
      logger.debug @interaction.errors.full_messages
      render 'new'
    end
    

    当您使用多个变量调用 form_for [@context, @interaction] 时,表单构建器无法看到之前的 @interaction 错误 ActiveModel::Errors:0x007f62d4221698,我不知道确切原因,但表单构建器似乎创建一个没有错误的新 ActiveModel::Errors。

    您只需要使用对象@interaction 指定f.object,该对象具有来自create 方法的错误对象。您可以在下面看到解决方案。

      <%= form_form [@context, @interaction] do |f| %>
      <% render 'shared/errors', object: @interaction %>
    

    【讨论】:

    • 感谢您的坚持。我会尽力回复你。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多