简体   繁体   中英

How to handle error messages in polymorphic associations for rails?

I have been following a polymorphic association tutorial at this website https://www.richonrails.com/articles/polymorphic-associations-in-rails

Unfortunately, the author did not provide the second-half of the tutorial.

I wonder what is correct syntax for handling error messages.

In interactions/new.html.erb,

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

In 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 %>

When a user try to enter a new interaction in error, says excess words limit, it is supposed to tell user that. However, nothing would happen.

It is easy if it is not polymorphic association, <%= form_form @interaction do |f| %> would work.

I have tried <%= form_form [@context, @interaction] do |f| %> <% render 'shared/errors', object: f.[@context, @interaction] %> It did not work.

Any clues for me? Thanks in advance! (ruby 2.3.3, rails 5.0.1)

Just figured this out today! May not explain this the best but the issue is that when errors happen and the form is re-rendered, the errors are saved to the object (@interaction) that you were calling save on (@interaction.save). It creates this error object ActiveModel::Errors:0x007f62d4221698. If you "logger.debug @interaction.errors.full_messages" in create method, you can see the error 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

When you call the form_for [@context, @interaction] with multiple variables the form builder cannot see the previous @interaction errors ActiveModel::Errors:0x007f62d4221698, I don't know the exact reason why, but the form builder seems to create a new ActiveModel::Errors which has no errors.

You just need to specified the f.object with the object @interaction that has the error object from the create method. Below you can see the solution.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM