Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Use of lambda with scopes in model

Hi I'm currently reading Rails Recipes and there's one section where the author uses scopes in the model so that the controller has access to certain query fragments without adding queries to the controller (and therefore violating the MVC rules). At one point he has this:

class Wombat < ActiveRecord::Base
  scope :with_bio_containing, lambda {|query| where("bio like ?", "%#{query}%").
                                         order(:age) }
end

I've never used lambda and Proc objects. Is this the equivalent of adding an argument to the scope so that conceptually it's scope :with_bio_containing(query) and therefore allowing me to customize the scope as if it were a function? Is lambda commonly used in scopes in Rails?

like image 489
bigpotato Avatar asked Nov 21 '12 19:11

bigpotato


People also ask

What is scope how and when it is to be used in Rails models?

Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.

What is the use of scope in Rails?

Scopes are used to assign complex ActiveRecord queries into customized methods using Ruby on Rails. Inside your models, you can define a scope as a new method that returns a lambda function for calling queries you're probably used to using inside your controllers.

What is the use of lambda in Ruby?

Ruby lambdas allow you to encapsulate logic and data in an eminently portable variable. A lambda function can be passed to object methods, stored in data structures, and executed when needed. Lambda functions occupy a sweet spot between normal functions and objects.

What is the difference between scope and class method Rails?

Scopes are just class methods. Internally Active Record converts a scope into a class method. "There is no difference between them" or “it is a matter of taste”.


1 Answers

In concept, you are right. It's like sending an argument. You would call this particular scope like so:

Wombat.with_bio_containing("born in Canada")

You could make a scope that takes in many arguments:

# code
scope :with_name_and_age, lambda { |name, age| where(:name => name, :age => age) }

# call
Wombat.with_name_and_age("Joey", 14)

You can also have no arguments:

# code
scope :from_canada, lambda { where(:country => "Canada") }

# call
Wombat.from_canada

And yes, lambdas are usually used from my own experience.

like image 193
MrDanA Avatar answered Sep 29 '22 02:09

MrDanA