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
类驱动程序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请勾选接受我的答案:)哎呀,对不起!