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

4
  • Care to explain what you want your default scope to be? Why do you want to use a Lambda? Commented Nov 25, 2011 at 6: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. Commented Nov 25, 2011 at 6:21
  • I would make a named scope for this, let me see if I can get an example for you. One moment. Commented Nov 25, 2011 at 6:24
  • Alright take a look at my answer and see if it works for you. Commented Nov 25, 2011 at 6:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks @DevinM for solutions but can't we do this with default scope?
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.
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.
So there always scoped? What about an admin interface for the application?
There is no such admin user to control all account. Every account has admin user who can control corresponding account only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.