Ruby on rails Rails 4:验证的属性唯一性有很多关系

Ruby on rails Rails 4:验证的属性唯一性有很多关系,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个冰箱,我想能够把产品放在冰箱里。听起来不错,但有两条规则: 冰箱里每种产品只有一个容量 有一套明确的产品,我可以放在冰箱里。冰箱的最大容量为: 1块奶酪 一个鸡蛋 一杯牛奶 1黄油 1个甜椒 1生菜 模型如下所示: class Product < ActiveRecord::Base belongs_to :fridge # Type product enum type: [:cheese, :egg, :milk, :butter, :bell_peppe

我有一个冰箱,我想能够把产品放在冰箱里。听起来不错,但有两条规则:

  • 冰箱里每种产品只有一个容量
  • 有一套明确的产品,我可以放在冰箱里。冰箱的最大容量为:

    • 1块奶酪
    • 一个鸡蛋
    • 一杯牛奶
    • 1黄油
    • 1个甜椒
    • 1生菜
  • 模型如下所示:

    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
    
    类产品

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

    您可以执行以下操作:

    app/validators/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
    

    对只需阅读有关自定义验证的指南。
    class Product < ActiveRecord::Base
      include ActiveModel::Validations
      validates_with MyValidator
      belongs_to :fridge
    
    end
    
    config.autoload_paths += %W["#{config.root}/app/validators/"]