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'

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

I want the User to be able to have one and only one car. This implies the fact that if he creates a machine assigned to him, he will not be able to create a second.

How can I do that?

+5
source share
3 answers

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

if worker.car
 raise "sorry buddy, no car for you"
else
 car = Car.create(user_id: worker.id)
end
+2
source

, , . , , user_id . , . - .

add_index(:cars, :worker_id, :unique => true)

- ( , , , ). . - , .

. . , , .

.

validates_uniqueness_of :worker_id, message: "can not have more than one car"

, - " ". , " ". , .

, , db, - , . "" Rails.

+15

Change the definition of the relationship a little:

class User < ActiveRecord::Base
  has_one :car

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

And you install what you are looking for. See: http://guides.rubyonrails.org/association_basics.html#the-has-one-association

+8
source

All Articles