matiss
matiss

Reputation: 747

Rails 5.1: retrieve records for nested association with includes

I'm trying to implement includes in has_many / belongs_to association similar to this example:

class Author < ApplicationRecord
  has_many :books, -> { includes :line_items }
end

class Book < ApplicationRecord
  belongs_to :author
  has_many :line_items
end

class LineItem < ApplicationRecord
  belongs_to :book
end

At the moment when I do @author.books I see in my console it loads Book and LineItem and shows records of Book, no records for LineItem. I get undefined method error when I try @author.books.line_items. Nor does @author.line_items work.

How do I get LineItem records for Author, please? Thank you!

Upvotes: 3

Views: 398

Answers (1)

MatayoshiMariano
MatayoshiMariano

Reputation: 2116

You will need to add a has_many association to Author.

Like this: has_many :line_items, through: :books, source: :line_items.

Then if you do author.line_items, then you wil get the LineItem records for the Author.

The way you are using the includes method, allows you to access the line_items through the books. Something like this: author.books.first.line_items, this code will not go to the database because the includes you have in has_many :books, -> { includes :line_items } autoloaded the line_items

Upvotes: 5

Related Questions