嵌套属性中的 Rails/Mongoid 错误消息
我有一个如下定义的联系信息类:
class ContactInfo
include Mongoid::Document
validates_presence_of :name, :message => ' cannot be blank'
field :name, :type => String
field :address, :type => String
field :city, :type => String
field :state, :type => String
field :zip, :type => String
field :country, :type => String
embedded_in :user
end
此联系信息类作为嵌套属性嵌入到我的用户类中:
class PortalUser
include Mongoid::Document
accepts_nested_attributes_for :contact_info
end
当我尝试保存没有名称的用户时,我收到如下错误消息:
联系信息无效
但是,这对最终用户来说不是很有用,因为他或她不知道哪些联系信息无效。真实消息应该是“名称不能为空”。然而,这个错误并没有向上传播。有没有办法在 user.errors 中获取“名称不能为空”消息,而不是“联系信息无效”错误消息?
谢谢
I have a contact info class defined like this:
class ContactInfo
include Mongoid::Document
validates_presence_of :name, :message => ' cannot be blank'
field :name, :type => String
field :address, :type => String
field :city, :type => String
field :state, :type => String
field :zip, :type => String
field :country, :type => String
embedded_in :user
end
This contact info class is embedd as a nested attribute inside my user class:
class PortalUser
include Mongoid::Document
accepts_nested_attributes_for :contact_info
end
When I attempt to save a user without a name, I get an error message like this:
Contact info is invalid
However, this is not very useful to the end user, because he or she doesn't know what contact info is invalid. The REAL message should be 'Name cannot be blank'. However, this error is not being propagated upwards. Is there a way to get the 'Name cannot be blank' message inside the user.errors instead of the 'Contact info is invalid' error message?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是我最终想出的解决方案:
将这些行添加到用户类中
Here's the solution I eventually came up with:
Added these lines to the user class
不是返回 user.errors.full_messages 而是为您的用户模型创建一个特定的错误消息方法,您可以在其中处理所有嵌入的文档错误。
并在你的控制器中
Instead of returning the user.errors.full_messages create a specific error message method for your user model where you handle all your embedded document errors.
and in your controller
我的解决方案涵盖了每个嵌入文档验证错误,如下所示:
My solution that covers each embedded document validation error is the following:
控制器中可能有一个解决方案...
在创建操作中,您可以添加类似
params[:portal_user][:contact_info_attributes] = {} if params[:portal_user] && 的 内容params[:portal_user][:contact_info_attributes].nil?
这将强制创建 contact_info,并会在右侧字段上触发错误
如果不添加此内容,则不会创建 contact_info
There might be a solution in the controller...
in the create action you can add something like
params[:portal_user][:contact_info_attributes] = {} if params[:portal_user] && params[:portal_user][:contact_info_attributes].nil?
This will force contact_info creation, and will trigger an error on the right field
If you don't add this, contact_info is not created