Using Named Scopes Across Models with ActiveRecord#Merge Discussion
I am doing it with subquery
Like
Author.where(id: Book.available.select(:author_id))
I agree that your version is cleaner and easier to remember,
but you might want to add .distinct after joins to avoid duplicated authors.
Ah yes, great points! I like that as a subquery and definitely need the distinct for my example as well.
Well, this is useful, but ugly... Thinking about querying, im not supposed to "merge" anything. IMHO
My wish was Author.books.scope(:available), lol
Well you can do Author.books.available because that's just querying Book.where(author_id: X).available. But obviously this is for the more complex joining tables case, so at least you're working with the models like you normally would. Not the best, but it saves you from duplication.
Minor nitpick: but I really think you mean `ActiveRecord::Relation#merge`, not `ActiveRecord#merge`
Big thanks! Had a default scope on my Model but rails 4.2.5 didn't unscope it when I was doing "each do" so using the .joins(:model).merge(Model.scope) you suggested instead
Could do something like:
scope :has_available_books, -> { joins(:books).merge(Book.available) }
Then you could just do:
Author.has_available_books
Need to note that merges on the same attribute overrides each other.
class Book < ActiveRecord::Base
...
scope :red, ->{ where(color: "red") }
scope :green, ->{ where(color: "green") }
end
Author.joins(:books).merge(Book.red).merge(Book.green)
^ would apply only green, because overwrite previous merge