From f183668ff92f220183f58d6779126a11feaf4d04 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 14:35:17 +1000 Subject: Querying guide: Add mention of the scope method --- .../guides/source/active_record_querying.textile | 42 ++++++++++++++++++++++ 1 file changed, 42 insertions(+) (limited to 'railties/guides/source') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index b9ad7ccbd2..fe6d284239 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -721,6 +721,48 @@ h4. Specifying Conditions on Eager Loaded Associations Even though Active Record lets you specify conditions on the eager loaded associations just like +joins+, the recommended way is to use "joins":#joining-tables instead. +h3. Scopes + +Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. + +To define a simple scope, we use the +scope+ method inside the class, passing the ARel query that we'd like run when this scope is called: + + + class Post < ActiveRecord::Base + scope :published, where(:published => true) + end + + +Just like before, these methods are also chainable: + + + class Post < ActiveRecord::Base + scope :published, where(:published => true).joins(:category) + end + + +Scopes are also chainable within scopes: + + + class Post < ActiveRecord::Base + scope :published, where(:published => true) + scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0)) + end + + +To call this +published+ scope we can call it on either the class: + + + Post.published => [published posts] + + +Or on an association consisting of +Post+ objects: + + + category = Category.first + category.posts.published => [published posts, belonging to this category] + + h3. Dynamic Finders For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +first_name+ on your +Client+ model for example, you get +find_by_first_name+ and +find_all_by_first_name+ for free from Active Record. If you have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+ methods. -- cgit v1.2.3