带有 lambda 和 Rails 4 样式参数的范围? [英] scopes with lambda and arguments in Rails 4 style?
问题描述
我想知道以下是如何在 Rails 4 中完成的,或者我是否只使用 Rails 3 方法来使用 lambda,该 lambda 可以像使用 3 一样使用 4 传递参数.
I'm wondering how the following is done in Rails 4 or if I just use the Rails 3 approach for using a lambda that can pass an argument the same way with 4 as I do with 3.
我对 Rails 3 还很陌生,正在尝试研究一些运行 Rails 4 的示例.
I'm pretty new to Rails 3 and trying to work through some samples running Rails 4.
这是我的 Rails 3 代码:
Here is my Rails 3 code:
class Person < ActiveRecord::Base
scope :find_lazy, lambda {|id| where(:id => id)}
end
# In console I can call
Person.find_lazy(1)
所以,如果这是 Rails 4 使用 -> {} 的方式,那就是 lambda,对吗?scope :all_lazy, ->{ select("*") }
如果我需要一个参数怎么办.我尝试了一些不同的想法,并在使用 -> {} 时在控制台中出现参数错误.
So if this is the Rails 4 way is to use the -> {}, that's a lambda, right? scope :all_lazy, -> { select("*") }
What if I needed an argument. I tried a few different ideas and get argument errors in the console when using the -> {}.
推荐答案
我觉得应该是:
scope :find_lazy, -> (id) { where(id: id) }
这篇关于带有 lambda 和 Rails 4 样式参数的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!