Rails 3:在模型中使用带作用域的 lambda [英] Rails 3: Use of lambda with scopes in model

查看:70
本文介绍了Rails 3:在模型中使用带作用域的 lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在阅读 Rails Recipes,其中有一个部分作者在模型中使用了作用域,以便控制器可以访问某些查询片段,而无需向控制器添加查询(因此违反了 MVC 规则).有一次他有这个:

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

我从未使用过 lambda 和 Proc 对象.这是否等同于向范围添加一个参数,以便从概念上讲它是 scope :with_bio_ contains(query) 并因此允许我自定义范围,就好像它是一个函数一样?在 Rails 的作用域中经常使用 lambda 吗?

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?

推荐答案

在概念上,您是对的.这就像发送一个论点.您可以像这样调用这个特定的范围:

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)

你也可以没有参数:

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

# call
Wombat.from_canada

是的,我通常根据自己的经验使用 lambda.

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

这篇关于Rails 3:在模型中使用带作用域的 lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆