with_scope

- 1.0.0 (0)
- 1.1.6 (18)
- 1.2.6 (0)
- 2.0.3 (6)
- 2.1.0 (1)
- 2.2.1 (2)
- 2.3.8 (5)
- 3.0.0 (-4)
- 3.0.9 (-2)
- 3.1.0 (0)
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
with_scope(method_scoping = {}, action = :merge, &block)
public
Scope parameters to method calls within the block. Takes a hash of method_name => parameters hash. method_name may be :find or :create. :find parameters may include the :conditions, :joins, :include, :offset, :limit, and :readonly options. :create parameters are an attributes hash.
Article.with_scope(:find => { :conditions => "blog_id = 1" }, :create => { :blog_id => 1 }) do Article.find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1 a = Article.create(1) a.blog_id # => 1 end
In nested scopings, all previous parameters are overwritten by inner rule except :conditions in :find, that are merged as hash.
Article.with_scope(:find => { :conditions => "blog_id = 1", :limit => 1 }, :create => { :blog_id => 1 }) do Article.with_scope(:find => { :limit => 10}) Article.find(:all) # => SELECT * from articles WHERE blog_id = 1 LIMIT 10 end Article.with_scope(:find => { :conditions => "author_id = 3" }) Article.find(:all) # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1 end end
You can ignore any previous scopings by using with_exclusive_scope method.
Article.with_scope(:find => { :conditions => "blog_id = 1", :limit => 1 }) do Article.with_exclusive_scope(:find => { :limit => 10 }) Article.find(:all) # => SELECT * from articles LIMIT 10 end end

:find takes more keys than written
The documentation says that the :find keywords “may include the :conditions, :joins, :include, :offset, :limit, and :readonly options”. Note that this does not mean that only those options are supported. :sort also works like it should, for example.

Rails 3.2 / 4.x with_scope replacement
If you’re looking for with_scope replacement for newer versions, see http://apidock.com/rails/ActiveRecord/Relation/scoping