Ruby on Rails - How to delegate error messages fro

2019-08-06 18:13发布

问题:

class User
  include Mongoid::Document

  has_many :images
  accepts_nested_attributes_for :image
end


class Image
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Paperclip

  has_mongoid_attached_file :uploaded_image,
    :path => ":rails_root/public/uploads/:class/:id/:basename.:extension",
    :url => "public/uploads/"
    validates_attachment_content_type :uploaded_file, :content_type => "application/png", :message => "error massage"
     belongs_to :user
    delegate :url, :path, to: :uploaded_image, allow_nil: true, prefix: false
end

How to delegate errors from Image to User if :uploaded_image is invalid?

For example:

user_image = user.images.build(uploaded_image: new_image.path)
user_image.save

Should rise a error if uploaded_image is invalid.

回答1:

Rails has the validates_associated helper (also available in Mongoid) which will call valid? upon each one of the associated objects.

The default error message for validates_associated is "is invalid". Note that each associated object will contain its own errors collection; errors do not bubble up to the calling model.

Rails Guides: Active Record Validations

class User
  include Mongoid::Document

  has_many :images
  accepts_nested_attributes_for :image
  validates_associated :images
end

Note that you should not add validates_associated :user to Image since it would cause an infinite loop.

You can access the errors for the nested images like so:

<% if @user.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
    <ul>
    <% @user.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
    <% if @user.images.any? %>
    <ul>
      <% @user.images.each do |image| %>
        <% if image.errors.any? %>
        <li>
          <ul>
            <% image.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
            <% end %>
          </ul>
        </li>
        <% end %>
      <% end %>
    </ul>
    <% end %>
  </div>
<% end %>