代码之家  ›  专栏  ›  技术社区  ›  hcarreras Scotty Rogers

验证此下面的状态_to

  •  1
  • hcarreras Scotty Rogers  · 技术社区  · 14 年前

    我有产品和品牌 产品型号:

    class Product < ActiveRecord::Base
      attr_accessible :brand_id, :title
      belongs_to :brand
    
      validates :title, :presence => true
      validates :brand, :presence => {:message => 'The brand no exists'}
    end
    

    和品牌模型

    class Brand < ActiveRecord::Base
      attr_accessible  :name
      validates :name, :presence => true
    
      has_many :products, :dependent => :destroy
    end
    

    我想验证这个品牌中是否存在同名产品。 我的意思是,我可以有两种不同品牌的同名产品,但不能在同一品牌。

    1 回复  |  直到 14 年前
        1
  •  1
  •   lcoq    14 年前

    你可以使用 uniqueness 使用验证 scope 以下为:

    validates :name, :uniqueness => { :scope => :brand_id }
    

    请注意,您必须指定 :brand_id 而不是 :brand ,因为无法对关系进行验证。

    如果你不知道,我建议你阅读 Active Record Validations and Callbacks 指导

    注意:语法 {:foo => 'bar'} 替换为(自Ruby 1.9.2以来) {foo: 'bar'} 。