Ask A Question


You’re not receiving notifications from this thread.

Querying Named Scopes Across Models with ActiveRecord::Relation#merge Discussion

Thank you for sharing, Chris, really awesome feature.


Did not know this. Very nice.


Great tip, Chris! Thanks for sharing. However, I notice (at 2:53) that your query `Author.joins(:books).merge(Book.available)` returns the same author three times. I'm not a SQL pro, so perhaps that's the normal behavior for this query, but not what I would expect when trying to return "all of the authors that have an available book". Any suggestions for de-duping the results from `merge()`? I'm sure a `uniq()` on the end would do the trick, but wonder if ActiveRecord has a way to do this right in the DB.


It depends on the type of JOIN you do. There's a bunch of different ways to do it, but take a look at this. It's one of the better things out there to explain the different JOINs.


Hello, Chris! Thank you for your education!

I try make it by using association at DataBase. So i use:

** Author.books.available**

And its work! Whats way is better (merge or method above )?

P.S. Sorry for my English.


Yes that works! You should use your version, not the merge for this.




Thank you sharing this wonderful feature of ActiveRecord


Thank you for your education!

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 73,895+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.