Ruby on Rails latest stable (v5.2.3) - 0 notes - Class: ActiveRecord::NamedScope::ClassMethods

Method deprecated or moved

This method is deprecated or moved on the latest stable version. The last existing version (v3.1.0) is shown here.

scoped(options = nil) public

Returns an anonymous scope.

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(:colour => 'red') if options[:red_only]
fruits = fruits.limit(10) if limited?

Anonymous scopes tend to be useful when procedurally generating complex queries, where passing intermediate values (scopes) around as first-class objects is convenient.

You can define a scope that applies to all finders using ActiveRecord::Base.default_scope.

Show source
Register or log in to add new notes.