Using lambda with named scopes in Rails 3

You can define an ActiveRelation named scope inside your model Address, for example, like so:

class Address < ActiveRecord::Base
  scope :search, lambda {|query| where(["name LIKE ?", "%#{query}%"])}
end
VN:F [1.9.22_1171]
Rating: 3.8/5 (6 votes cast)
VN:F [1.9.22_1171]
Rating: +3 (from 5 votes)
Using lambda with named scopes in Rails 3, 3.8 out of 5 based on 6 ratings
Facebook Twitter Email

2 Comments to “Using lambda with named scopes in Rails 3”

  1. Vairamuthu 9 August 2012 at 11:28 pm #

    Hi,

    Please let us know the difference between the two named_scope and class method.

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)
  2. megatux 17 January 2012 at 10:09 am #

    You can also use a class method like this

    def self.search(query)
    where([“name LIKE ?”, “%#{query}%”])
    end

    if you don’t like the lambda syntax

    VA:F [1.9.22_1171]
    Rating: 4.7/5 (3 votes cast)
    VA:F [1.9.22_1171]
    Rating: +1 (from 3 votes)

Leave a Reply