From 28b1642561cddc1f8650f7a8c740ece259db913b Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 23 Dec 2010 14:50:40 +1000 Subject: Query guide: lambdas must be used when working with scopes --- railties/guides/source/active_record_querying.textile | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'railties') diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index fe6d284239..25f3723b93 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -763,6 +763,18 @@ Or on an association consisting of +Post+ objects: category.posts.published => [published posts, belonging to this category] +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. + + + class Post < ActiveRecord::Base + scope :last_week, lambda { where("created_at < ?", Time.zone.now ) } + end + + +Without the +lambda+, this +Time.zone.now+ will only be called once. + 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