Reputation: 1335
Hi I have a rails App which displays always the company name on each page. Since a logged in user can have multiple companies she belongs to. User and companies are stored in the db. I use authlogic for the user management.
Now I do not want to hit the database on every postback or page change What would be best practise to chache/store the company until the logged in users changes or the user selects a different company? Something like global instance vars for a given user.
I started with this in my application_controller
def current_company
return @current_company if defined?(@current_company)
@current_company = Account.includes(:users).where(:users =>current_company)
end
and I realized that I am still hitting the db...
Is the session the recommended way or what would be best practice for this...
Thanks for the help in advance
Upvotes: 0
Views: 969
Reputation: 571
||= way:
def current_company
@current_company ||= Account.includes(:users).where(:users =>current_company)
end
memoize way:
def current_company
Account.includes(:users).where(:users =>current_company)
end
memoize :current_company
Differences between this method and normal memoization with ||=
http://apidock.com/rails/ActiveSupport/memoize#447-Differences-between-normal-or-assign-operator
@tadman, you are right but from my point of view depends how complex its the method that you are trying to "cache". For simple cases I prefer ||=
Upvotes: 2
Reputation: 8757
I think this is what you're looking for https://github.com/nkallen/cache-money
Upvotes: 0