我需要确保产品创建时至少有一个类别。 我可以用自定义验证类来做到这一点,但我希望有一个更标准的方法来做到这一点。验证对象是否有一个或多个关联对象
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_many'的好机会http://api.rubyonrails.org/classes/ActiveRecor d /协会/ ClassMethods.html#方法-I-has_and_belongs_to_many。除非不想在关联中存储其他属性,否则不需要连接模型。 2.你可以使用这个问题的最佳答案http://stackoverflow.com/questions/6429389/how-can-i-make-sure-my-has-many-will-have-a-size-of-at-至少2猜测你必须改变:) – jibiel 2012-03-02 15:36:57