Ruby on rails 验证此应用程序中的存在是否属于
我有产品和品牌 产品型号:Ruby on rails 验证此应用程序中的存在是否属于,ruby-on-rails,ruby,ruby-on-rails-3,belongs-to,Ruby On Rails,Ruby,Ruby On Rails 3,Belongs To,我有产品和品牌 产品型号: 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 类产品true 验证:品牌,:存在=>{
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
类产品true
验证:品牌,:存在=>{:消息=>'品牌不存在'}
结束
以及品牌模式
class Brand < ActiveRecord::Base
attr_accessible :name
validates :name, :presence => true
has_many :products, :dependent => :destroy
end
class品牌true
有很多:产品,:依赖=>:销毁
结束
我想验证是否存在此品牌中有名称的产品。
我的意思是,我可以在不同的品牌中拥有两种名称相同的产品,但不在同一品牌中。您可以使用
唯一性验证和范围
:
validates :name, :uniqueness => { :scope => :brand_id }
请注意,您必须指定:brand\u id
,而不是:brand
,因为无法对关系进行验证
如果你不知道,我建议你读一下指南
注意:语法{:foo=>'bar'}
被{foo:'bar'}
替换(从Ruby 1.9.2开始),您可以使用唯一性验证和范围
:
validates :name, :uniqueness => { :scope => :brand_id }
请注意,您必须指定:brand\u id
,而不是:brand
,因为无法对关系进行验证
如果你不知道,我建议你读一下指南
注意:语法{:foo=>'bar'}
被{foo:'bar'}
替换(从Ruby 1.9.2开始)