aboutsummaryrefslogtreecommitdiffstats
path: root/railties/guides/source/active_record_querying.textile
diff options
context:
space:
mode:
authorRyan Bigg <radarlistener@gmail.com>2010-12-23 14:57:53 +1000
committerRyan Bigg <radarlistener@gmail.com>2010-12-23 14:57:53 +1000
commit0644e38c4269c06968cacd60ac677011af82671c (patch)
treee09d91a2490762174ca1002b991e1dd9338336b2 /railties/guides/source/active_record_querying.textile
parentb4b2574a12f7a3b6db97d28eda894ad872445190 (diff)
downloadrails-0644e38c4269c06968cacd60ac677011af82671c.tar.gz
rails-0644e38c4269c06968cacd60ac677011af82671c.tar.bz2
rails-0644e38c4269c06968cacd60ac677011af82671c.zip
Query guide: scopes with arguments should be instead defined as class methods.
Diffstat (limited to 'railties/guides/source/active_record_querying.textile')
-rw-r--r--railties/guides/source/active_record_querying.textile34
1 files changed, 31 insertions, 3 deletions
diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile
index 5cd302f356..eb77a35739 100644
--- a/railties/guides/source/active_record_querying.textile
+++ b/railties/guides/source/active_record_querying.textile
@@ -768,13 +768,41 @@ h4. Working with times
If you're working with dates or times within scopes, due to how they are evaluated, you will need to use a lambda so that the scope is evaluated every time.
<ruby>
- class Post < ActiveRecord::Base
- scope :last_week, lambda { where("created_at < ?", Time.zone.now ) }
- end
+class Post < ActiveRecord::Base
+ scope :last_week, lambda { where("created_at < ?", Time.zone.now ) }
+end
</ruby>
Without the +lambda+, this +Time.zone.now+ will only be called once.
+h4. Passing in arguments
+
+When a +lambda+ is used for a +scope+, it can take arguments:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :1_week_before, lambda { |time| where("created_at < ?", time)
+end
+</ruby>
+
+This may then be called using this:
+
+<ruby>
+Post.1_week_before(Time.zone.now)
+</ruby>
+
+However, this is just duplicating the functionality that would be provided to you by a class method.
+
+<ruby>
+class Post < ActiveRecord::Base
+ def self.1_week_before(time)
+ where("created_at < ?", time)
+ end
+end
+</ruby>
+
+Using a class method is the preferred way to accept arguments for scopes.
+
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.