I’m trying to generate a simple navigation pane to include in my
application.rhtml. The nav pane consists of dynamic link_to tags that
are generated from data in a model.
I’m now used to doing trivial MVC operations in a template:
But what if I want to generate the @departments in application.rb? I
have no action to place it in (like index), and it does not seem to work
at the class level:
class ApplicationController < ActionController::Base @departments = Department.find(:all)
end
Should this work and be available in application.rhtml as @departments? If so then thats good news and my syntax is just wrong.
if not, is there an alternative way to populate an object in
application.rb and use it in application.rhtml?
Should this work and be available in application.rhtml as @departments? If so then thats good news and my syntax is just wrong.
This would only run when the controller class is first loaded, which
is probably not what you want. It’s also an instance variable of the class and not of the request, so you can’t access it from the view
in the same way.
if not, is there an alternative way to populate an object in
application.rb and use it in application.rhtml?
The MVC police might arrest me, but I see no problem with just putting
the find directly in the view in this case. If the find became
elaborate, I would refactor the complexity back into a model class
method (much easier to test, and keeps the view code as simple as
possible).
I don’t like the before_filter approach. It would unecessarily
retrieve the departments even if you weren’t rendering the view (e.g.
an xhr response or a post-redirect), it pollutes the request
namespace, and it prevents optimization through fragment caching.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.