Pass arguments in scope

2020-02-23 05:00发布

问题:

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)

Thanks

回答1:

new syntax (ruby 1.9+), that will prevent errors even if you don't supply the user -

scope :default_permissions_for, ->(user = nil) { ... }


回答2:

Use lambda scopes:

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.