Ruby on Rails - 如何从嵌套模型委派错误消息

时间:2015-06-18 18:42:46

标签: ruby-on-rails ruby ruby-on-rails-4 mongoid paperclip

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

如果:uploaded_image无效,如何将错误从Image委托给用户?

例如:

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

如果uploaded_image无效,则会出现错误。

1 个答案:

答案 0 :(得分:1)

Rails有validates_associated助手(在Mongoid中也可用),它会在每个关联对象上调用valid?

  

validates_associated的默认错误消息是“无效”。   请注意,每个关联的对象都将包含自己的错误   采集;错误不会冒泡到调用模型。

     

Rails Guides: Active Record Validations

class User
  include Mongoid::Document

  has_many :images
  accepts_nested_attributes_for :image
  validates_associated :images
end

注意您不应将validates_associated :user添加到Image,因为它会导致无限循环。

您可以访问嵌套图像的错误,如下所示:

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