Rails 5.1: getting records for a nested link with included

I am trying to implement includes in has_many

/ associations belongs_to

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

      

The moment I do @author.books

I can see that in my console it downloads Book

and LineItem

and shows records Book

, there are no records for LineItem

. I am getting undefined method error when trying @author.books.line_items

. Doesn't work @author.line_items

.

How do I get the LineItem

entries for Author

please? Thank!

+3


source to share


1 answer


You need to add the association has_many

to Author

.

Example has_many :line_items, through: :books, source: :line_items

.



Then, if you follow through author.line_items

, you get the entries LineItem

for the author.

As you use the includes method , you can access it line_items

through the books. Something like this:, author.books.first.line_items

this code will not go to the database, because includes

you have it has_many :books, -> { includes :line_items }

automatically loadedline_items

+5


source







All Articles