使用关联范围的唯一性字段



我想确保项目名称在组织中是唯一的。因此,我在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

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

如果以上不可能。我想我可以在item和item_category中有一个organization_id。但是,我们如何验证item.organization_id始终等于item_category.organization_id(其关联)

项目中不包含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

最新更新