2014-02-06 87 views

回答

0

而且這個怎麼樣?但不知何故,我對此沒有信心..

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 
0

檢查單輪

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 
相關問題