3

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!

MatayoshiMariano
  • 2,026
  • 19
  • 23
matiss
  • 747
  • 15
  • 36

1 Answers1

5

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

MatayoshiMariano
  • 2,026
  • 19
  • 23
  • 2
    the `source` option is optional in this case (see https://stackoverflow.com/questions/4632408/need-help-to-understand-source-option-of-has-one-has-many-through-of-rails) – MrYoshiji Aug 07 '17 at 16:50
  • 1
    Thank you, this is nice :) Works like charm! For me it seemed to work when I changed to `source: :line_items` - like plural. Maybe typo there. – matiss Aug 07 '17 at 17:13
  • @matiss yes it is a typo! Edited! – MatayoshiMariano Aug 07 '17 at 17:14