Topic: Dynamic navigation menu using Menuitem model

Hi all,

I am using this table to store navigation links in db:


class CreateMenuitems < ActiveRecord::Migration
  def self.up
     create_table :menuitems do |t|
        t.column :title, :string, :limit => 100, :null => false
        t.column :url, :string, :null => false
        t.column :parent_id, :integer, :default => 0
     end
  end

  def self.down
    drop_table :menuitems
  end
end


Model Menuitem uses ACTS_AS_TREE. What is the best way to render Menuitems in all views (layouts)? Using partial, component rendering or helper?

Thanks!

Re: Dynamic navigation menu using Menuitem model

Try a partial first. If that requires too much logic then move it into a helper. Components should be avoided if possible.

Railscasts - Free Ruby on Rails Screencasts

Re: Dynamic navigation menu using Menuitem model

Thanks for reply. I am working on.

Re: Dynamic navigation menu using Menuitem model

Hi all again,

I am successfully generating menu with partials. Now I am solving related problem. My menu consists of lists. It looks like this:

Root1      
|- subitem1
|- subitem2
|- ...

Root2
|- subitem11
|- subitem12
   |-subsubitem1
|- ...

RootN
|-...


I need assign specific CSS style to the Root if its subitem is choosen

I know sollution for the case if all subitems in the list have one controller (checking current controller name).

But in my project is the main problem that URLs of subitems are handled by various controllers.

Any idea?

Re: Dynamic navigation menu using Menuitem model

radosh wrote:

I need assign specific CSS style to the Root if its subitem is choosen

How is a subitem considered "chosen"? You just need to find a way to check that.

Railscasts - Free Ruby on Rails Screencasts

Re: Dynamic navigation menu using Menuitem model

ryanb wrote:

How is a subitem considered "chosen"?

When you click on a subitem. Subitem's URL is rendered. And in this time I need assign style to the Root item.

ryanb wrote:

You just need to find a way to check that.

Yes, question is how to check it.

Suppose, one way is adding menuitem's ID to the URL.

http://example.com/subitem's_url?MID=menuitemid

And after that check, if the Root item contains a subitem with id=MID.

Is there any better solution?

Re: Dynamic navigation menu using Menuitem model

How about looping through the children and calling current_page? on each of them.

Railscasts - Free Ruby on Rails Screencasts

Re: Dynamic navigation menu using Menuitem model

ryanb wrote:

How about looping through the children and calling current_page? on each of them.

Good idea, I will try it. Thanks Ryan.