What's the difference between belongs_to and has_one?

前端 未结 5 494
有刺的猬
有刺的猬 2020-11-28 02:04

What is the difference between a belongs_to and a has_one?

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

5条回答
  •  没有蜡笔的小新
    2020-11-28 02:56

    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
    end
    

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

提交回复
热议问题