Instance variables in components not read by component view?


#1

Hi,

I’m trying to write a sidebar menu with dynamic menus, and to do so I
would like to define a list of menus to display within my sidebar
component controller code and pass that list to the component display
view, like so:

menu_controller.rb

class Sidebar::MenuController < ActionController::Base
uses_component_template_root

@menus = %w{admin user help}

def display
@display_menu = params[:menu]
render(:layout => false)
end
end

menu/display.rhtml

<% @menus.each do |menu| %> <%= link_to_remote "#{menu}",:url => { :controller => "sidebar/menu", :action => 'toggle_menu', :menu => "#{menu}" } %>
<%= render_component(:controller => "sidebar/menu", :action => "#{menu}_menu") %>
<% end %>

When trying to run display.rhtml, I get errors saying @menu == nil
instead of Array. Now if I replace the display @menus loop with this:

<% (%w{admin user help}).each do |menu| %>

it works as expected.

I’ve tried putting @menus both within the display method and outside it
in the class definition. Am I not understanding the component concept
correctly? The Rails book demonstrates component controller classes
passing instance variables to the views (pp. 376-377, look for get_links
and @links) so what am I missing?

TYVMIA,

  • Matt

#2

Matthew-

You need to put the menu initialization in a before filter. Then it

will work like you want.:

menu_controller.rb

class Sidebar::MenuController < ActionController::Base
uses_component_template_root

before_filter :setup_menu
attr_accessor :menu

def display
@display_menu = params[:menu]
render(:layout => false)
end

private

def setup_menu
@menus = %w{admin user help}
end

end

That will do exactly what you want.

Cheers-
-Ezra

On Feb 19, 2006, at 11:27 AM, Mathew Hennessy wrote:

<% @menus.each do |menu| %>
instead of Array. Now if I replace the display @menus loop with this:
get_links
http://lists.rubyonrails.org/mailman/listinfo/rails

-Ezra Z.
WebMaster
Yakima Herald-Republic Newspaper
removed_email_address@domain.invalid
509-577-7732


#3

excellent, that did the trick, thanks!