Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 249
cgf Avatar asked Feb 26 '13 20:02

cgf


1 Answers

Change the definition of the relationship slightly:

class User < ActiveRecord::Base
  has_one :car

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

And you'll establish what you're looking for. See: http://guides.rubyonrails.org/association_basics.html#the-has-one-association

like image 184
Richard Brown Avatar answered Sep 19 '22 08:09

Richard Brown