Search code examples
sqlruby-on-railshas-manybelongs-to

ruby on rails - difference between using JUST 'belongs_to' versus using BOTH 'has_many' and 'belongs_to'?


What is the difference between using just belongs_to on one model versus having has_many on one and belongs_to on another?

As an example:

class Author < ActiveRecord::Base
end

class Book < ActiveRecord::Base
  belongs_to :author
end

versus

class Author < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :author
end

Thank you.


Solution

  • guessing each of the methods would facilitate adding a different set of additional methods to the associated class

    for ex, if had to guess, with belongs_to, you would, in part, get ability to call association on an instance of Book:

    @book.author
    

    with has_many, if I had to guess, you would, in part, be able to call association on instance of Author:

    @author.books
    

    also, http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to

    and

    http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

    in case those may be of interest