Denny Mueller
Denny Mueller

Reputation: 3615

Difference between has_one and belongs_to on a 1 to many relationship in Ruby on Rails

The idea is that i have a table users and a table customers. Each user has many customers that are related only to them. Actually Im using this model. So every customer that will be created will also get the related user_id in the customers table.

class Customer 
  belongs_to :user
end

class User
  has_many :customers
end

After some SO question it was stated to me that I should use this model, for the same result.

class Customer
  has_one :user
end

class User
  belongs_to :customer
end

But i dont get the difference. Any easy explaination wether Im right with my way or what is wrong.

regards denym

Upvotes: 1

Views: 266

Answers (1)

Raindal
Raindal

Reputation: 3237

It won't actually be the same result...

The first one:

class Customer 
  belongs_to :user
end

class User
  has_many :customers
end

Will set a user_id in the Customer and nothing in the User. That means that a customer can only be related to one user. In terms of reflections you can do stuff like this:

user = User.create(name: 'John Snow')
customer = user.customers.build(name: 'Tywin Lannister')
customer.save

user.inspect
=> #<User id: 8, name: "John Snow">

customer.inspect
=> #<Customer id: 12, user_id: 8, name: "Tywin Lannister">

user.customers.inspect 
=> [#<Customer id: 12, user_id: 8, name: "Tywin Lannister">]

customer.user
=> #<User id: 8, name: "John Snow">

The second one:

class Customer
  has_one :user
end

class User
  belongs_to :customer
end

Will set a customer_id in the user. You can do stuff like this:

customer = Customer.create(name: 'Tywin Lannister')
user = customer.build_user(name: 'John Snow')

user.inspect
=> #<User id: 8, customer_id: 12, name: "John Snow">

customer.inspect
=> #<Customer id: 12, name: "Tywin Lannister">

user.customer
=> #<Customer id: 12, name: "Tywin Lannister">

customer.user
=> #<User id: 8, customer_id: 12, name: "John Snow">

So in your case

Well you need the first one.

From the documentation:

A belongs_to association sets up a one-to-one connection with another model, such that each instance of the declaring model “belongs to” one instance of the other model.

A has_one association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model.

Upvotes: 2

Related Questions