使用关联范围的唯一性字段
Uniqueness field using Scope of association
我想确保项目名称在组织内是唯一的。所以我在 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?
如果以上都做不到。我想我可以在项目中有一个 organization_id 和 item_category。但是那么我们如何验证 item.organization_id 总是等于 item_category.organization_id(它的关联)
It is okay to not include the organization_id inside an item?
是的,不包括因为 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
我想确保项目名称在组织内是唯一的。所以我在 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?
如果以上都做不到。我想我可以在项目中有一个 organization_id 和 item_category。但是那么我们如何验证 item.organization_id 总是等于 item_category.organization_id(它的关联)
It is okay to not include the organization_id inside an item?
是的,不包括因为 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