Why does the Rails manual suggest using the scoped method for associations?
The Rails guide states that a scope can be called in associations. But then later , it says that a method scoped
that returns an object ActiveRecord::Relation
"might be useful ... on associations." If scope can be called on an association, what additional functionality scoped
does it provide ?
+3
source to share
1 answer
scoped
returns the anonymous scope. In the API docs:
Anonymous scopes are generally useful in procedural generation of complex queries where the convenience of passing intermediate values (scopes) around first class objects.
Here's an example:
posts = Post.scoped
posts.size # Fires "select count(*) from posts" and returns the count
posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
fruits = Fruit.scoped
fruits = fruits.where(:color => 'red') if options[:red_only]
fruits = fruits.limit(10) if limited?
+2
source to share