Search code examples
ruby-on-railsactiverecordruby-on-rails-2

using lambda with default scope


I'm facing lil problem using lambda with default_scope in rails 2.3.

default_scope lambda { {:account_id => account_id } }

I used above code but error message is displayed ArgumentError: wrong number of arguments (1 for 0)

Am I using lambda worng way?

Thanks


Solution

  • Alright, what you would want is to use is a named scope, that way you can have other scopes in the future. Usually you want to stay away from changing the default scope because it would affect other queries.

    The code below creates a named scope called current_account and it ensures that all records match the condition, the account_id of the record must match the current account_id.

    named_scope :current_account, :conditions => { :account_id => account_id }
    

    Then when you want to use the named_scope you can call the code below:

    User.current_account.all
    

    This is just like calling:

    User.all(:conditions => { :account_id => account_id })
    

    Hope this helps you, let me know if anything is confusing.