命名范围和命名范围有什么区别+拉姆达
name_scope 和named_scope + lambda Ruby on Rails 代码语句之间有什么区别?
named_scope :with_avatar, :conditions => ['avatar IS NOT NULL']
和
named_scope :date_from, lambda { |date| { :conditions => ['created_at >= ?', DateTime.strptime(date, '%d.%m.%Y')] } }
What is a difference between named_scope and named_scope + lambda Ruby on Rails code statements?
named_scope :with_avatar, :conditions => ['avatar IS NOT NULL']
and
named_scope :date_from, lambda { |date| { :conditions => ['created_at >= ?', DateTime.strptime(date, '%d.%m.%Y')] } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 lambda,您可以指定作用域的参数。
在上述情况下,您可以说
Model.with_avatar 和 Model.date_from("10.08.2010"),但是您不能说 Model.with_avatar( false)
在这种情况下,您需要对 lambda 的参数小心一些:除非您将参数传递给 date_from,否则它可能不起作用。一种“解决方法”是使用 |*date| ,检查它是否已传入,如果没有则将其设置为某个默认值。
With the lambda, you can specify arguments to the scope.
In the above case, you could say
Model.with_avatar and Model.date_from("10.08.2010"), however you cannot say for example Model.with_avatar(false)
In this case, you need to be somewhat careful about the arguments to the lambda: unless you pass an argument to date_from, it will probably not work. One "workaround" is to use |*date| , check if it was passed in and set it to some default value if it wasn't.