I've just replaced a whole stack of nasty hand-coded SQL with nested scopes. There is a lot you can do with them that you aren't quite able to do with the standard associations. The main benefit is that you don't lose find_in_collection
which all the examples seem to neglect. It's pretty rare that you want everything in a table. You mostly want to sort it and slice it, or search through it. So finder_sql
isn't useful for very much. It doesn't provide any value that a standard method with some custom SQL search doesn't provide.
class User
def public_topics(*options)
Topic.with_user_scope(self) { Topic.with_public_scope { Topic.find(*options) }
end
end
I was able to replace a nasty SQL subquery with this. And even swiftier, you can give it your normal ActiveRecord::Base.find
options. It's probably not clear why I couldn't just use normal associations here, but I really couldn't. There was a topic_relationships
table which connected users to topics very oddly, which is what created all the headaches.
So the moral of the story is, with_scope
is the probably best option when normal associations won't cut it.
Comments
No comments yet.
Leave a comment