Ruby on Rails-如何从嵌套模型中委派错误消息 [英] Ruby on Rails - How to delegate error messages from nested model
问题描述
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无效,如何将错误从图像委托给用户?
How to delegate errors from Image to User if :uploaded_image is invalid?
例如:
user_image = user.images.build(uploaded_image: new_image.path)
user_image.save
如果upload_image无效,应该引发错误.
Should rise a error if uploaded_image is invalid.
推荐答案
Rails具有validates_associated
帮助器(在Mongoid中也可用),该帮助器将在每个关联对象上调用valid?
.
Rails has the validates_associated
helper (also available in Mongoid) which will call valid?
upon each one of the associated objects.
validates_associated的默认错误消息为无效". 请注意,每个关联的对象将包含其自己的错误 收藏;错误不会上升到调用模型.
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.
class User
include Mongoid::Document
has_many :images
accepts_nested_attributes_for :image
validates_associated :images
end
请注意,请勿将validates_associated :user
添加到Image
,因为这会导致无限循环.
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 %>
这篇关于Ruby on Rails-如何从嵌套模型中委派错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!