简体   繁体   English

Rails 3:在模型中使用lambda和范围

[英]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). 嗨我正在阅读Rails Recipes,并且有一个部分,作者在模型中使用范围,以便控制器可以访问某些查询片段而无需向控制器添加查询(因此违反了MVC规则)。 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. 我从未使用过lambda和Proc对象。 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? 这相当于在范围中添加一个参数,以便在概念上它的scope :with_bio_containing(query) ,因此允许我自定义范围,就好像它是一个函数一样? Is lambda commonly used in scopes in Rails? lambda是否常用于Rails中的范围?

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. 是的,lambdas通常是根据我自己的经验使用的。

Yes to both questions. 这两个问题都是。

Wombat.with_bio_containing('foo') is evaluated at runtime into something like: Wombat.with_bio_containing('foo')在运行时被评估为:

select * from wombats where bio like "%foo%" order by age

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM