0

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

2 Answers 2

2

||= 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 ||=

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

4 Comments

The ||= method is great for plain Ruby, but in Rails you may want to use the memoize method as it's more flexible.
This applies only per page request? Or I am I wrong. When I hit refresh I hit the database... I want to define it in the Application_controller because it show on every page. Am I on the wrong path
Anything attached to an instance of your controller will be for one request only. Anything attached to the class will persist for the lifespan of the process. Note however this data is not shared between instances of Rails, of which there are usually several on any active site.
0

I think this is what you're looking for https://github.com/nkallen/cache-money

1 Comment

Looks good but does not support Rails 3 and I am targeting Rails 3... are you using it with rails 3?

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.