【问题标题】:Validate presence in this belongs_to验证此 belongs_to 中的存在
【发布时间】:2012-09-07 11:25:31
【问题描述】:

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

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

我想验证是否存在具有该品牌名称的产品。 我的意思是我可以有 2 个不同品牌的同名产品,但不是同一个品牌。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 belongs-to


    【解决方案1】:

    您可以将uniqueness 验证与scope 一起使用:

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

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

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

    注意:语法 {:foo =&gt; 'bar'} 被替换为 {foo: 'bar'}(自 Ruby 1.9.2 起)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多