[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 end
- If foo
belongs_to :bar, then the foos table has a
- If foo
has_one :bar, then the bars table has a
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
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
class User < ActiveRecord::Base # I reference an account. belongs_to :account end class Account < ActiveRecord::Base # One user references me. has_one :user end
The tables for these classes could look something like:
CREATE TABLE users ( id int(11) NOT NULL auto_increment, account_id int(11) default NULL, name varchar default NULL, PRIMARY KEY (id) ) CREATE TABLE accounts ( id int(11) NOT NULL auto_increment, name varchar default NULL, PRIMARY KEY (id) )
What is the difference between a
belongs_to and a
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
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 end
This will add method 'author' to Book model.
For mode details see guides