Reputation: 29797
The Rails guides state that a scope can be called on an association. But then further on, it states that the scoped
method, which returns an ActiveRecord::Relation
object, "may come in handy...on associations". If a scope can be called on an association, what additional functionality does scoped
provide?
Upvotes: 3
Views: 96
Reputation: 114208
scoped
returns an anonymous scope. From the API docs:
Anonymous scopes tend to be useful when procedurally generating complex queries, where passing intermediate values (scopes) around as first-class objects is convenient.
Here's the 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?
Upvotes: 2