45

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

Jason Swett
  • 43,526
  • 67
  • 220
  • 351
glarkou
  • 7,023
  • 12
  • 68
  • 118

2 Answers2

83

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

scope :default_permissions_for, ->(user = nil) { ... }
Nuriel
  • 3,731
  • 3
  • 23
  • 23
  • very helpful info. So does this mean when the argument is nil, the block doesn't execute? Ruby just behaves that way? – ahnbizcad Aug 25 '14 at 07:53
  • nope, it only means that the user will get a default value of nil if no value is given. the block will run, but you could check if user.nil? – Nuriel Aug 25 '14 at 08:01
  • Thanks for the clarification. Heh, that's what the wording made it sound like, even though my ruby logic was screaming, "Wouldn't nil just get passed in as the argument?" – ahnbizcad Aug 25 '14 at 13:08
38

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.

Mark Hurd
  • 10,665
  • 10
  • 68
  • 101
keymone
  • 8,006
  • 1
  • 28
  • 33
  • Is it possible to show an example on how to catch this exception in the controller? Or it's not necessary? – glarkou Jul 22 '11 at 09:48
  • i'm not sure about exception name, check it in your logs and just do rescue ExceptionClass => e – keymone Jul 23 '11 at 20:58
  • 8
    @keymone in ruby 1.9 you can set a default for the lambda parameter to avoid those errors you're referring to. So it would be lambda{|user = nil| { :conditions...... – Dorian Apr 21 '13 at 00:29