【发布时间】:2012-03-21 01:22:49
【问题描述】:
我需要确保在创建产品时它至少具有一个类别。 我可以使用自定义验证类来做到这一点,但我希望有一种更标准的方式来做到这一点。
class Product < ActiveRecord::Base
has_many :product_categories
has_many :categories, :through => :product_categories #must have at least 1
end
class Category < ActiveRecord::Base
has_many :product_categories
has_many :products, :through => :product_categories
end
class ProductCategory < ActiveRecord::Base
belongs_to :product
belongs_to :category
end
【问题讨论】:
-
1.产品 + 类别是认识
has_and_belongs_to_manyapi.rubyonrails.org/classes/ActiveRecord/Associations/… 的绝佳机会。除非您不想在关联旁边存储其他属性,否则您不需要加入模型。 2.你可以使用这个问题的最佳答案stackoverflow.com/questions/6429389/…猜你要改变什么:)
标签: ruby-on-rails validation has-many-through