Menu displayed on all pages, code is replicated in all controllers
I have a collection model. I succesfully created a _collection.html.erb
that i call with <%= render @collections%>
in my application layout.
My problem is that in ALL my controlers method I must add @collections = Collection.all
I found it very very ugly,it will make my collection scope a pain to change开发者_如何学JAVA, and I'm sure that I am missing a rails magic something that would be way nicer.
Is there a way to have a part of the layout generated by model data without having a identical piece of code in AAAALLLLLL the controllers?
Notice that your controllers all inherit from ApplicationController
. Use this to your advantage. Add a before_filter
to ApplicationController
that loads your collections.
@cam was right. Any rails project has an ApplicationController. Your controllers all start with MyController < ApplicationController, right? If so, that means you can create a before_filter in your ApplicationController, which will be inherited by all your controllers. To do so :
/app/controllers/application_controller.rb
before_filter :load_collection
def load_collection
@collections = Collection.all
end
From now on, you can use @collections from all your controllers (as long as they inherited from ApplicationController)
精彩评论