Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.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 4 Rails 4如何验证具有唯一列值的多个_Ruby On Rails 4_Rails Activerecord - Fatal编程技术网

Ruby on rails 4 Rails 4如何验证具有唯一列值的多个

Ruby on rails 4 Rails 4如何验证具有唯一列值的多个,ruby-on-rails-4,rails-activerecord,Ruby On Rails 4,Rails Activerecord,这是提供的示例: has_many :spam_comments, -> { where spam: true }, class_name: 'Comment' 是否可以执行以下操作: class Driver < ActiveRecord::Base belongs_to :vehicle end class Vehicle < ActiveRecord::Base has_many :drivers, -> { where('name').distinct

这是提供的示例:

has_many :spam_comments, -> { where spam: true }, class_name: 'Comment'
是否可以执行以下操作:

class Driver < ActiveRecord::Base
  belongs_to :vehicle
end

class Vehicle < ActiveRecord::Base
  has_many :drivers, -> { where('name').distinct }
end
类驱动程序{where('name').distinct} 结束 我的场景不是一个has\u many-through,这就是为什么我删除了class\u name:子句

我试图实现的是防止驾驶员被装载到车辆集合中,除非驾驶员姓名是唯一的

herbie = Vehicle.create(name: 'Herbie')
fred = Driver.create(name: 'Fred')

herbie.drivers << fred

herbie.drivers << fred # This second association should not work.
herbie=Vehicle.create(名称:“herbie”)
fred=驱动程序。创建(名称:“fred”)

herbie.drivers您可以在此处使用
范围
唯一性选项

在您的
Driver
model中,添加以下内容

validates_uniqueness_of :name, scope: :vehicle_id
此外,还应添加如下迁移:

add_index :drivers, [ :vehicle_id, :name ], :unique => true

避免比赛条件。有关更多信息,请检查

为什么不能在此处使用唯一性验证。像
验证:name的唯一性,并且对name设置唯一性约束是个坏主意。如果两个或两个以上的人有相同的名字“Fred”怎么办?在这种特殊情况下,名字可以相同,但同名司机不能使用同一辆车。在这种情况下,这只是一个人为的例子,但逻辑适用于我正在处理的一个真实场景,涉及车辆品牌和车型。你能发布你的
驾驶员
车型吗?这非常有效!谢谢我假设您建议在迁移中添加索引。是的!在迁移中添加索引:)@Claymoton请勾选接受我的答案:)哎呀,对不起!