How to display error messages in a multi-model form with transaction?

后端 未结 5 1266
长情又很酷
长情又很酷 2021-01-23 06:53

Two models, Organization and User, have a 1:many relationship. I have a combined signup form where an organization plus a user for that organization get signed up.

The p

5条回答
  •  北恋
    北恋 (楼主)
    2021-01-23 07:22

    This is very related to this question. The key is that <%= render 'shared/error_messages', object: f.object %> is, I assume, only calling the .errors method on the object it is passed (in this case, organization).

    However, because the user errors reside with the user object, they won't be returned and therefore will not be displayed. This requires simply changing the view logic to also display the results of .errors on the various user models. How you want to do so is up to you. In the linked thread, the accepted answer had the error message display code inline instead of in a partial, so you could do it that way, but it would be somewhat redundant.

    I would modify my shared/error_messages.html.erb file to check for another passed local called something like nested_models. Then it would use that to search the associated models and include the errors on that. We just would need to check whether it is defined first so that your other views that don't have a nested model won't cause it to raise an error.

    shared/error_messages.html.erb

    <% if object.errors.any? %>
      
    Object Errors:
      <% object.errors.full_messages.each do |msg| %>
    • <%= msg %>
    • <% end %>
    <% if defined?(nested_models) && nested_models.any? %> Nested Model(s) Errors:
      <% nested_models.each do |nested_model| %> <% unless nested_model.valid? %>
      • <% nested_model.errors.full_messages.each do |msg| %>
      • <%= msg %>
      • <% end %>
    • <% end %> <% end %>
    <% end %>
    <% end %>

    Then you would just need to change a single line in your view:

    <%= render partial: 'shared/error_messages', locals: { object: @organization, nested_models: @organization.users } %>
    

提交回复
热议问题