Home > OS >  Return every row from has_many association after filter
Return every row from has_many association after filter

Time:04-26

Having models Author and Book where Author has_many books, and a scope on the Author like:

scope :by_books,->(book_ids) { joins(:books).where(books: { id: book_ids }) }

with the intent of filtering Authors if they are authors of a given book, results only the author and the specified books only in the result of:

Author.by_books(1).includes(:books).as_json(include: :books)

Whereas I would expect to have all the books of the author in the resulting json. I can do that by using .joins(:books) instead of .includes(:books) but now I am completely confused about what joins and includes do. I wonder if somebody could give me an explanation where my expectation goes wrong.

(The code given is an analog of my actual, it might be flawed in terms of syntax but I believe the behavior is the same)

CodePudding user response:

  • joins is a pure SQL word query to join 2 tables.
  • includes is for eager loading (avoid n 1 query issue)

  • Related