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是无效的?
例如:
user_image = user.images.build(uploaded_image: new_image.path)
user_image.save
应该上升一个错误,如果uploaded_image无效。
轨有validates_associated
助手(在Mongoid也可用),这将调用valid?
于相关联的对象中的每一个。
对于validates_associated的默认错误信息是“无效”。 需要注意的是每个关联对象将包含它自己的错误集合; 错误不冒泡需要调用模型。
Rails的指南:活动记录验证
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 %>