Ruby on rails Rails通过集合创建模型\u id如何防止重新关联?
假设我有两个模型Ruby on rails Rails通过集合创建模型\u id如何防止重新关联?,ruby-on-rails,validation,Ruby On Rails,Validation,假设我有两个模型 class Car < ActiveRecord::Base has_many :wheels end class Wheel < ActiveRecord::Base belongs_to :car end class-Car
class Car < ActiveRecord::Base
has_many :wheels
end
class Wheel < ActiveRecord::Base
belongs_to :car
end
class-Car
将使用车轮ID为[1,2,3]的汽车创建汽车
如何检查某个车轮是否已与另一辆车关联?检查单个车轮
wheel = Wheel.last
wheel.car.present? # => if false then it has no association to car
检查无关联的所有车轮
wheels = Wheel.join(:car).where(:car => { :id => nil}) # => not tested yet but should work
这个怎么样?但不知何故,我对这一点没有信心
class Car < ActiveRecord::Base
validate :check_reassociation_wheels, on: [:create,:update]
def check_reassociation_wheels
wheel_ids.each do |id|
wheel = Wheel.find(id)
errors.add(:base, "Cannot reasociate wheel") unless (wheel.car_id.nil? || wheel.car_id == self.id)
end
end
end
class-Car