验证对象是否具有一个或多个关联对象

rec*_*nym 34 validation ruby-on-rails has-many-through

我需要确保在创建产品时它至少有一个类别.我可以使用自定义验证类来完成此操作,但我希望有一种更标准的方法.

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
Run Code Online (Sandbox Code Playgroud)

小智 60

有一个验证将检查您的关联长度.试试这个:

class Product < ActiveRecord::Base
  has_many :product_categories
  has_many :categories, :through => :product_categories

  validates :categories, :length => { :minimum => 1 }
end
Run Code Online (Sandbox Code Playgroud)

  • 如何编写规范来测试它? (3认同)

Adr*_*ian 40

确保它至少有一个类别:

class Product < ActiveRecord::Base
  has_many :product_categories
  has_many :categories, :through => :product_categories

  validates :categories, :presence => true
end
Run Code Online (Sandbox Code Playgroud)

我发现使用的错误消息:presence比使用length minimum 1验证更清晰