views:

38

answers:

1

What is a difference between named_scope and named_scope + lambda Ruby on Rails code statements?

named_scope :with_avatar, :conditions => ['avatar IS NOT NULL']

and

named_scope :date_from, lambda { |date| { :conditions => ['created_at >= ?', DateTime.strptime(date, '%d.%m.%Y')] } }
+2  A: 

With the lambda, you can specify arguments to the scope.

In the above case, you could say

*Model.with_avatar* and *Model.date_from("10.08.2010")*, however you cannot say for example *Model.with_avatar(false)*

In this case, you need to be somewhat careful about the arguments to the lambda: unless you pass an argument to date_from, it will probably not work. One "workaround" is to use |*date| , check if it was passed in and set it to some default value if it wasn't.

Zaki