Rails AR validates_uniqueness_of 针对多态关系
是否可以验证子模型属性在多态关系范围内的唯一性?
例如,我有一个名为 field
的模型,属于 fieldable
:
class Field < ActiveRecord::Base
belongs_to :fieldable, :polymorphic => :true
validates_uniqueness_of :name, :scope => :fieldable_id
end
我还有其他几个模型(页面、项目),它们有许多字段。所以我想要的是根据父模型验证字段名称的唯一性,但问题是有时页面和项目共享相同的 ID 号,导致验证在不应该失败的时候失败。
我只是做错了还是有更好的方法来做到这一点?
Is it posible to validate the uniqueness of a child model's attribute scoped against a polymorphic relationship?
For example I have a model called field
that belongs to fieldable
:
class Field < ActiveRecord::Base
belongs_to :fieldable, :polymorphic => :true
validates_uniqueness_of :name, :scope => :fieldable_id
end
I have several other models (Pages, Items) which have many Fields. So what I want is to validate the uniqueness of the field name against the parent model, but the problem is that occasionally a Page and an Item share the same ID number, causing the validations to fail when they shouldn't.
Am I just doing this wrong or is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需扩大范围以包括可现场类型:
Just widen the scope to include the fieldable type:
您还可以添加一条消息来覆盖默认消息,或者使用范围来添加验证:
如果您转到 en.yml,并输入以下内容,则会得到额外的好处:
您将替换 Rails 添加到的默认“主题”您在此处指定的错误。因此,它不会说:
Fieldable Id has not been take
左右,而是说:You can also add a message to override the default message, or use scope to add the validation:
As a bonus if you go to your en.yml, and enter:
You are going to replace the default 'subject' that rails add to the errors with the one you specify here. So instead of saying:
Fieldable Id has been already taken
or so, it would say: