Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 验证此应用程序中的存在是否属于_Ruby On Rails_Ruby_Ruby On Rails 3_Belongs To - Fatal编程技术网

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开始)