我有冰箱,我希望能够将产品放入冰箱。听起来不错,但有两条规则:
我可以将一组定义的产品放入冰箱。冰箱的最大容量是:
模型看起来像这样:
class Product < ActiveRecord::Base
belongs_to :fridge
# Type product
enum type: [:cheese, :egg, :milk, :butter, :bell_pepper, :lettuce]
end
class Fridge < ActiveRecord::Base
has_many :products
end
是否可以在冰箱模型中设置验证器以满足定义的规则?
答案 0 :(得分:1)
您可以这样做:
应用程序/验证/ my_validator.rb
class MyValidator < ActiveModel::Validator
def validate(record)
types = record.fridge.products.select(:type).map &:type
type = record.type
if types.include? type
record.errors[:name] << 'Only 1 capacity for each product'
end
end
end
然后在app / models / product.rb
中添加自定义验证程序class Product < ActiveRecord::Base
include ActiveModel::Validations
validates_with MyValidator
belongs_to :fridge
end
还要记得将它添加到config / application.rb中以加载路径:
config.autoload_paths += %W["#{config.root}/app/validators/"]