铁路模型:将 validates_uniqueness_of 与关联实体的属性范围一起使用?

发布于 2024-10-24 23:26:34 字数 553 浏览 1 评论 0原文

我的模型定义如下,

    class One <Active:Record:Base
    {
         has_and_belongs_to_many :twos, {:join_table => 'map__ones__twos'}
    }

    class Two <Active:Record:Base
    {
         has_and_belongs_to_many :ones, {:join_table => 'map__ones__twos'}
    }

我希望两个的名称属性对于一个的范围应该是唯一的。这意味着属于一个人的所有两人都应该有唯一的名字。在这里,我无法在两个模型中指定如下所示的内容,

      validates_uniqueness_of :name, :scope => one_id

因为 on_id 不是二元表的列。相反,one_id 和two_id 通过表map_ones_twos 相互映射(多对多关系)

请建议

I have Model defined as below

    class One <Active:Record:Base
    {
         has_and_belongs_to_many :twos, {:join_table => 'map__ones__twos'}
    }

    class Two <Active:Record:Base
    {
         has_and_belongs_to_many :ones, {:join_table => 'map__ones__twos'}
    }

I want that name attribute of two should be unique for scope of one. That means all of twos belonging to one should have unique name. Here i can not specify some thing like below in Two model

      validates_uniqueness_of :name, :scope => one_id

because on_id is not a column of twos table. Rather one_id and two_id are mapped to each other through table map_ones_twos (many to many relationship)

Please suggest

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

兲鉂ぱ嘚淚 2024-10-31 23:26:34

我经常发现使用 has_and_belongs_to_many 麻烦多于其价值。当我有多对多关系时,我创建一个连接表并为其创建一个模型。然后,连接模型可以验证两个 id 的唯一性。

请原谅这些名字。我正在使用您问题中的示例表名称。在你的情况下,这看起来像:

class MapOnesTwo < ActiveRecord::Base
  belongs_to :one
  belongs_to :two

  validates_presence_of :one_id, :two_id
  validates_uniqueness_of :one_id, :scope => :two_id
end

你的一个模型看起来像这样:

class One < ActiveRecord::Base
  has_many :ones_twos, :dependent => :destroy
  has_many :twos, :through => :ones_twos
end

你的两个模型看起来像这样:

class Two < ActiveRecord::Base
  has_many :ones_twos, :dependent => :destroy
  has_many :twos, :through => :ones_twos
end

I have often found that using has_and_belongs_to_many is more trouble than it's worth. When I have many-to-many relationships, I create a join table and make a model for it. Then, the join model can have a validation on the uniqueness of the two ids.

Excuse the names. I am using the example table names from your question. In your case, this would look like:

class MapOnesTwo < ActiveRecord::Base
  belongs_to :one
  belongs_to :two

  validates_presence_of :one_id, :two_id
  validates_uniqueness_of :one_id, :scope => :two_id
end

Your One model looks like this:

class One < ActiveRecord::Base
  has_many :ones_twos, :dependent => :destroy
  has_many :twos, :through => :ones_twos
end

And your Two model looks like this:

class Two < ActiveRecord::Base
  has_many :ones_twos, :dependent => :destroy
  has_many :twos, :through => :ones_twos
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文