Search code examples
ruby-on-railsmodelsrelationshipone-to-one

About one to one relationship in Models in rails


I have three models

class Vehicle < ActiveRecord::Base
 has_one:driver ,:through=>:vehicle_driver
end

class Vehicle_Driver < ActiveRecord::Base
 belongs_to:vehicle
 belongs_to:driver
end

have only vehicle_id and driver_id

class Driver < ActiveRecord::Base
 has_one:vehicle_driver
end

I want to do is

  • register the vehicles independently

  • register the Drivers independently

  • then assign driver to vehicle such that only one driver can be assigned to one vehicle and vice versa

and further

  • if I assign driver to another vehicle its early relation must be deleted

Is this possible from above relationship ...?????

Any help will be appreciated..

Thanks In Advance


Solution

    1. Why the intermediate class, it contradicts your requirements, so remove it.

    2. So just let both models Vehicle and Driver use has_one of the other. It generates a duplicate relationship that could lead to problems, if they are not pointing to each other. So the best is to have only one 'has_one'-relationship, and do @vehicle.find_by_driver to test if a driver already has a vehicle assigned to it.

    3. When you save a relationship, also update the other relation: 3a @vehicle.driver = @driver 3b @vehicle.driver.vehicle = @vehicle # to force make them point to each other.

    4. In the Vehicle model, add a method or scope to return a list of vehicles where driver is nil. 4a Vehicle.all.where(:driver.nil?) # from my head, just to give an idea

    If you want to remove a relationship for a vehicle, do 5a @vehicle.driver.vehicle = nil 5b @vehicle.driver = nil

    Hope this helps you in the right direction.