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.17_1161]
Rating: 4.7/5 (3 votes cast)
VN:F [1.9.17_1161]
Rating: +3 (from 3 votes)
Using lambda with named scopes in Rails 3, 4.7 out of 5 based on 3 ratings

One Comment to “Using lambda with named scopes in Rails 3”

  1. 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.17_1161]
    Rating: 4.7/5 (3 votes cast)
    VA:F [1.9.17_1161]
    Rating: +1 (from 3 votes)

Leave a Reply