[Ruby-on-rails] What's the difference between belongs_to and has_one?


It's about where the foreign key sits.

class Foo < AR:Base
  • If foo belongs_to :bar, then the foos table has a bar_id column
  • If foo has_one :bar, then the bars table has a foo_id column

On the conceptual level, if your class A has a has_one relationship with class B then class A is the parent of class B hence your class B will have a belongs_to relationship with class A since it is the child of class A.

Both express a 1-1 relationship. The difference is mostly where to place the foreign key, which goes on the table for the class declaring the belongs_to relationship.

class User < ActiveRecord::Base
  # I reference an account.
  belongs_to :account

class Account < ActiveRecord::Base
  # One user references me.
  has_one :user

The tables for these classes could look something like:

  id int(11) NOT NULL auto_increment,
  account_id int(11) default NULL,
  name varchar default NULL,

CREATE TABLE accounts (
  id int(11) NOT NULL auto_increment,
  name varchar default NULL,

What is the difference between a belongs_to and a has_one?

Reading the Ruby on Rails guide hasn't helped me.

One additional thing that i want to add is, Suppose we have following models association

class Author < ApplicationRecord has_many :books end

if we only write the above association then we can get all books of a particular author by,

@books = @author.books

But for a particular book we can't get the corresponding author by,

@author = @book.author

to make the above code work work we need to add association to Book model also, like this

class Book < ApplicationRecord
  belongs_to :author

This will add method 'author' to Book model.
For mode details see guides