Rails 中的 Lambda 表示法。它是如何使用的?作用域中 lambda 表达式中括号中的参数是什么?
Lambda notation in Rails. How is it used? What is the argument in the parenthesis inside a lambda in a scope?
假设我有一个 Order
模型:
class Order < ActiveRecord::Base
scope :last_month, ->(object) { where(“publish_date > ?”, 1.month.ago) }
end
所以,这显然就是如何在 Rails 中定义范围。但是 lambda 括号内的对象是什么?如果 object
表示生成的 AR 集合...为什么这有意义?幕后发生了什么?为什么这里需要 Proc?
If object represents the resulting AR collection
不,object
表示范围的参数。如果你有这个范围,例如:
class User
scope :created_after, ->(timestamp) { where('created_at > ?', timestamp) }
end
那么你可以这样称呼它:
User.created_after(3.days.ago)
But what is the object inside that lambda parenthesis?
该行是语法糖:
lambda { |object| where("publish_date > ?", 1.month.ago) }
object
值是 lambda 的参数。
If object represents the resulting AR collection...why does that make sense?
正如 Sergio 所说,它代表您可以传递的额外参数。
What's going on behind the scenes? Why is a Proc needed here?
proc 更像是对旧问题的强制解决方案。所以当你习惯这样定义范围时:
scope :created_after, Time.now
Time.now 会在 rails 应用程序启动时立即 运行。因此它不会在每次 运行 范围时重新评估 Time.now。 Lambda 确保您的逻辑每次都执行。
假设我有一个 Order
模型:
class Order < ActiveRecord::Base
scope :last_month, ->(object) { where(“publish_date > ?”, 1.month.ago) }
end
所以,这显然就是如何在 Rails 中定义范围。但是 lambda 括号内的对象是什么?如果 object
表示生成的 AR 集合...为什么这有意义?幕后发生了什么?为什么这里需要 Proc?
If object represents the resulting AR collection
不,object
表示范围的参数。如果你有这个范围,例如:
class User
scope :created_after, ->(timestamp) { where('created_at > ?', timestamp) }
end
那么你可以这样称呼它:
User.created_after(3.days.ago)
But what is the object inside that lambda parenthesis?
该行是语法糖:
lambda { |object| where("publish_date > ?", 1.month.ago) }
object
值是 lambda 的参数。
If object represents the resulting AR collection...why does that make sense?
正如 Sergio 所说,它代表您可以传递的额外参数。
What's going on behind the scenes? Why is a Proc needed here?
proc 更像是对旧问题的强制解决方案。所以当你习惯这样定义范围时:
scope :created_after, Time.now
Time.now 会在 rails 应用程序启动时立即 运行。因此它不会在每次 运行 范围时重新评估 Time.now。 Lambda 确保您的逻辑每次都执行。