Rails AR validates_uniqueness_of 针对多态关系

发布于 2024-08-28 01:03:14 字数 400 浏览 8 评论 0原文

是否可以验证子模型属性在多态关系范围内的唯一性?

例如,我有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

葮薆情 2024-09-04 01:03:14

只需扩大范围以包括可现场类型:

class Field < ActiveRecord::Base
  belongs_to :fieldable, :polymorphic => :true
  validates_uniqueness_of :name, :scope => [:fieldable_id, :fieldable_type]
end

Just widen the scope to include the fieldable type:

class Field < ActiveRecord::Base
  belongs_to :fieldable, :polymorphic => :true
  validates_uniqueness_of :name, :scope => [:fieldable_id, :fieldable_type]
end
寄人书 2024-09-04 01:03:14

您还可以添加一条消息来覆盖默认消息,或者使用范围来添加验证:

class Field < ActiveRecord::Base
  belongs_to :fieldable, :polymorphic => :true
  validates_uniqueness_of :fieldable_id, :scope => [:fieldable_id, :fieldable_type], :message => 'cannot be duplicated'
end

如果您转到 en.yml,并输入以下内容,则会得到额外的好处:

  activerecord:
    attributes:
     field:
       fieldable_id: 'Field'

您将替换 Rails 添加到的默认“主题”您在此处指定的错误。因此,它不会说:Fieldable Id has not been take 左右,而是说:

 Field cannot be duplicated

You can also add a message to override the default message, or use scope to add the validation:

class Field < ActiveRecord::Base
  belongs_to :fieldable, :polymorphic => :true
  validates_uniqueness_of :fieldable_id, :scope => [:fieldable_id, :fieldable_type], :message => 'cannot be duplicated'
end

As a bonus if you go to your en.yml, and enter:

  activerecord:
    attributes:
     field:
       fieldable_id: 'Field'

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:

 Field cannot be duplicated
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文