【问题标题】:Uniqueness field using Scope of association使用关联范围的唯一性字段
【发布时间】:2015-11-19 18:49:20
【问题描述】:

我想确保项目名称在组织内是唯一的。所以我在 Item 中使用了“validates_uniqueness_of :name, scope: [:organization]”。不幸的是,这没有奏效。

错误(已编辑):

>   1) Item 
>      Failure/Error: @item_1 = create(:item, :item_category => @item_cat_1)
>      
>      NoMethodError:
>        undefined method `organization_id' for #<Item:0x00000002565840>

型号:

class Item < ActiveRecord::Base
  belongs_to :item_category
  has_one :organization, through: :item_category
  validates_uniqueness_of :name, scope: [:organization]
end

class ItemCategory < ActiveRecord::Base
    has_many :items
    belongs_to :organization
end

class Organization < ActiveRecord::Base
  has_many :item_categories
  has_many :items, :through => item_categories
end

理论上,正如我上面所做的那样,我可以使用项目的 item_category 关联(belongs_to :item_category)作为 organization_id 吗?

如果以上不可行。我想我可以在 item 和 item_category 中有一个 organization_id。但是我们如何验证 item.organization_id 总是等于 item_category.organization_id(它的关联)

【问题讨论】:

  • 您的业务要求是否要求所有项目在整个组织中都必须具有唯一的名称?不同 ItemCategories 中的重复名称可以吗?
  • 所有项目在整个组织中都必须具有唯一的名称。此外,由于 item_category 属于组织,因此您不应在组织范围内有重复的项目名称。希望澄清事情

标签: ruby-on-rails ruby-on-rails-4 activerecord rspec factory-bot


【解决方案1】:

可以不将 organization_id 包含在项目中吗?

是的,不包括,因为列 organization_id 将是多余的。

对于复杂的验证,我们通常使用自定义的验证,这是我的例子,你可以纠正它:

class Item < ActiveRecord::Base
  belongs_to :item_category
  has_one :organization, through: :item_category
  # validates_uniqueness_of :name, scope: [:organization]
  validate :check_uniqueness_of_name

  def check_uniqueness_of_name
    if Organization.includes(item_categories: :items).where.not(items: {id: self.id}).where(items: {name: self.name}).count > 0
      errors.add(:name, 'name was duplidated')
    end
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多