Reputation: 5269
I have an application which is used by several divisions, where each of them has a separate set of data. So i got many models with a division_id
field which indicates the division the row belongs to.
Each user has the division information also, so when they log in, i have to filter the data according to the division. So there are many places in my code where i do this for example:
Contact.where(division_id: current_user.division_id)
My question is how to refactor this code fragment? First i have thought about utilizing the default
scope of the ActiveRecord, but since the division_id
is a controller specific data, that didn't seem right. Any ideas?
Upvotes: 0
Views: 41
Reputation: 18037
I'm not sure why you say division_id
is controller-specific data because it looks like you're getting the division from the User object (current_user.division_id
). Anyway, the best thing to do would probably be just to make use of scopes here and then repeat the scope. For example:
# app/models/contact.rb
scope :for_user_division, -> user { where(division_id: user.division_id }
But it's still going to be repetitive calling e.g.
Contact.for_user_division(current_user)
everywhere. The main advantage is you can now change the rules of the scope in one place if you need to add something like only considering active?
divisions later.
I don't think there's need nor want to DRY this up further. In general, I think default scopes are a bad thing because, in cases like this, a little bit of repetition is useful in reminding yourself what it is your'e dealing with -- a limited set of Contacts.
UPDATE If you find yourself writing the same scope in more than one model then you can surely DRY up the scope by putting it into a concern and including it into each model as needed.
Upvotes: 1