Reputation: 7101
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
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
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