【问题标题】:Rail Model: Using validates_uniqueness_of with scope on attributes of associated entity?铁路模型:在关联实体的属性范围内使用 validates_uniqueness_of?
【发布时间】:2011-07-19 15:37:57
【问题描述】:

我的模型定义如下

    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(多对多关系)相互映射

请推荐

【问题讨论】:

  • 一和二不是好名字。请将您的示例更改为更可更改的内容。

标签: ruby-on-rails model scope has-and-belongs-to-many validates-uniqueness-of


【解决方案1】:

我经常发现使用 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

您的 One 模型如下所示:

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

您的 Two 模型如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 2012-03-09
    • 1970-01-01
    • 2017-08-29
    相关资源
    最近更新 更多