Forum: Ruby on Rails instance variables in components not read by component view?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Mathew H. (Guest)
on 2006-02-19 21:27
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
<div class="menu">
<% @menus.each do |menu| %>
<%= link_to_remote "#{menu}",:url => { :controller => "sidebar/menu",
:action => 'toggle_menu', :menu => "#{menu}" } %> <br>
<div id="<%= menu %>_menu" style="display: none">
<%= render_component(:controller => "sidebar/menu", :action =>
"#{menu}_menu") %>
</div>
<% end %>
</div>

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
Ezra Z. (Guest)
on 2006-02-19 23:38
(Received via mailing list)
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
Mathew H. (Guest)
on 2006-02-20 21:59
excellent, that did the trick, thanks!
This topic is locked and can not be replied to.