2

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

ashisrai_
  • 6,438
  • 2
  • 26
  • 42
  • Care to explain what you want your default scope to be? Why do you want to use a Lambda? – Devin M Nov 25 '11 at 06:11
  • i am running above code in application layer to set default scope for set of models so that i can easily get particular account's records with simple search say 'User.all' with User model. The problem is when i run above code for second time it still takes previous account id. I am not sure what the problem is but just wanted to give a try. – ashisrai_ Nov 25 '11 at 06:21
  • I would make a named scope for this, let me see if I can get an example for you. One moment. – Devin M Nov 25 '11 at 06:24
  • Alright take a look at my answer and see if it works for you. – Devin M Nov 25 '11 at 06:35

1 Answers1

2

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.

Devin M
  • 9,636
  • 2
  • 33
  • 46
  • Thanks @DevinM for solutions but can't we do this with default scope? – ashisrai_ Nov 25 '11 at 07:36
  • You could, I'm just saying that's a bad idea, what if you want records that dont use the scope? Then you have to call `User.unscoped` which is messy. – Devin M Nov 25 '11 at 21:32
  • That isn't the case. Its subdomain enabled app and always scoped records are used. Whenever `User.all` is run, the records of that subdomani(account) should return from `user` table. I think this makes sense. I never have to use `unscoped`. – ashisrai_ Nov 27 '11 at 02:36
  • So there always scoped? What about an admin interface for the application? – Devin M Nov 27 '11 at 03:47
  • There is no such admin user to control all account. Every account has admin user who can control corresponding account only. – ashisrai_ Nov 28 '11 at 03:04