enjaku enjaku - 2 months ago 11
Ruby Question

get all has_many associations in rails

Let's say I have two models

Author
and
Book
, where Author
has_many :books
and Book
belongs_to :author
. Is there a way to get all books by all authors without iterating through all the authors using
each
?

Answer

yea, you can use joins or includes, if you want get all books, which have someone Author

Book.includes(:author)

if you want to get all books, you can simply:

Book.all
Comments