with_scope
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 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(scope = {}, action = :merge, &block)
public
with_scope lets you apply options to inner block incrementally. It takes a hash and the keys must be :find or :create. :find parameter is Relation while :create parameters are an attributes hash.
class Article < ActiveRecord::Base def self.create_with_scope with_scope(:find => where(:blog_id => 1), :create => { :blog_id => 1 }) do find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1 a = create(1) a.blog_id # => 1 end end end
In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of where, includes, and joins operations in Relation, which are merged.
joins operations are uniqued so multiple scopes can join in the same table without table aliasing problems. If you need to join multiple tables, but still want one of the tables to be uniqued, use the array of strings format for your joins.
class Article < ActiveRecord::Base def self.find_with_scope with_scope(:find => where(:blog_id => 1).limit(1), :create => { :blog_id => 1 }) do with_scope(:find => limit(10)) do all # => SELECT * from articles WHERE blog_id = 1 LIMIT 10 end with_scope(:find => where(:author_id => 3)) do all # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1 end end end end
You can ignore any previous scopings by using the with_exclusive_scope method.
class Article < ActiveRecord::Base def self.find_with_exclusive_scope with_scope(:find => where(:blog_id => 1).limit(1)) do with_exclusive_scope(:find => limit(10)) do all # => SELECT * from articles LIMIT 10 end end end end
Note: the :find scope also has effect on update and deletion methods, like update_all and delete_all.