cgf cgf - 10 months ago 50
Ruby Question

Rails one-to-one relationship

I have the following:

class User < ActiveRecord::Base
has_one :car, :class_name => 'Car', :foreign_key => 'user_id'

class Car < ActiveRecord::Base
belongs_to :worker, :class_name => 'User', :foreign_key => 'user_id'

It is basically a one-to-one relationship between a user and a car.

What I want is for the User to be able to have one and only one car. That implies the fact that if he creates a car assigned to him, he won't be able to create the second.

How could this be done?


why don't you just test before the user tries to add a car?

 raise "sorry buddy, no car for you"
 car = Car.create(user_id: