glarkou
glarkou

Reputation: 7101

Pass arguments in scope

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

Upvotes: 45

Views: 35148

Answers (2)

keymone
keymone

Reputation: 8104

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.

Upvotes: 39

Nuriel
Nuriel

Reputation: 3741

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

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

Upvotes: 83

Related Questions