Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 387
glarkou Avatar asked Jul 22 '11 09:07

glarkou


2 Answers

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

scope :default_permissions_for, ->(user = nil) { ... }
like image 137
Nuriel Avatar answered Nov 05 '22 09:11

Nuriel


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.

like image 38
keymone Avatar answered Nov 05 '22 08:11

keymone