Rails 4:验证属性唯一性有很多关系

时间:2016-04-28 21:52:55

标签: ruby-on-rails ruby

我有冰箱,我希望能够将产品放入冰箱。听起来不错,但有两条规则:

  1. 冰箱中每种产品只有一种容量。
  2. 我可以将一组定义的产品放入冰箱。冰箱的最大容量是:

    • 1奶酪
    • 1个鸡蛋
    • 1牛奶
    • 1 Butter
    • 1 Bell Pepper
    • 1生菜
  3. 模型看起来像这样:

    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
    

    是否可以在冰箱模型中设置验证器以满足定义的规则?

1 个答案:

答案 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/"]