Ruby-on-rails 在范围内传递参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6788203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass arguments in scope
提问by glarkou
Can someone provide an example on how to use
有人可以提供一个关于如何使用的例子吗
scope
and parameters?
和参数?
For example:
例如:
class Permission < ActiveRecord::Base
scope :default_permissions, :conditions => { :is_default => true }
end
I have this code that returns the default_permissions and I want to convert it to return the default permissions for a given user (user_id)
我有这个返回 default_permissions 的代码,我想将它转换为返回给定用户(user_id)的默认权限
Thanks
谢谢
回答by Nuriel
new syntax (ruby 1.9+), that will prevent errors even if you don't supply the user -
新语法(ruby 1.9+),即使您不提供用户,也可以防止错误 -
scope :default_permissions_for, ->(user = nil) { ... }
回答by keymone
Use lambda scopes:
使用 lambda 范围:
scope :default_permissions_for, lambda{|user| { :conditions => { :user_id => user.id, :is_default => true } }
Be careful because not passing a parameter to a lambda when it expects one will raise an exception.
小心,因为当 lambda 预期会引发异常时,不要将参数传递给它。

