44

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
  • 41,074
  • 64
  • 208
  • 335
glarkou
  • 6,693
  • 11
  • 64
  • 118

2 Answers2

81

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,671
  • 3
  • 22
  • 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,435
  • 10
  • 65
  • 99
keymone
  • 7,726
  • 1
  • 26
  • 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