本文介绍了验证一个对象具有一个或多个关联对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要确保在创建产品时,它至少具有一个类别. 我可以使用自定义验证类来做到这一点,但我希望有一种更标准的方法来实现它.
I need to ensure that when a product is created it has atleast one category. I could do this with a custom validation class, but I was hoping there was a more standard way of doing it.
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推荐答案
有一个验证将检查您的关联的长度.试试这个:
There is a validation that will check the length of your association. Try this:
class Product < ActiveRecord::Base has_many :product_categories has_many :categories, :through => :product_categories validates :categories, :length => { :minimum => 1 } end更多推荐
验证一个对象具有一个或多个关联对象
发布评论