Reputation: 27
I'm in the process of creating my own simple blog application and I want to include a 'latest posts' section on the sidebar, so my posts model needs to be accessible by the entire app. I'm looking for the best way of doing so.
I'm thinking a before_filter in the application controller followed up a private method to call the scope I have:
class ApplicationController < ActionController::Base
before_filter :latest_news
private
def latest_news
@latest = News.latest.limit(5)
end
end
Is this the best way?
Upvotes: 0
Views: 39
Reputation: 18037
Instead of a before_filter
, I'd recommend using a lazy-load approach that does basically the same thing.
class ApplicationController < ActionController::Base
helper_method :latest_news
def latest_news
@latest_news ||= News.latest.limit(5)
end
end
This way you can call latest_news
from any controller or view (which is what the helper_method
macro does for you) and then it'll load it if it's not loaded already the first time it's called and any subsequent calls will be cached. This is a pretty common pattern for getting things like the current user record, etc.
Upvotes: 1