0

我想確保項目名稱在組織內是唯一的。所以我在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(其關聯)

+0

是你的業務需求,使得所有項目必須在整個組織具有唯一的名稱?在不同的ItemCategories中重複的名稱會好嗎? – messanjah

+0

所有項目在整個組織中必須具有唯一的名稱。另外,由於item_category屬於組織,因此組織範圍內不應有重複的項目名稱。希望澄清事情 – user1438150

回答

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