Rails,Mongoid-Ancestry:如果未选择父节点,则排除子节点

时间:2015-03-20 04:45:34

标签: ruby-on-rails mongoid ancestry

我有显示主菜单的代码:

@main_menu = Page.where(active: true).arrange(order: :position)

它将活动参数的所有节点设置为true。但是,如果某些子节点的父节点设置为active:false,则它们将连接到祖父节点,依此类推。如何避免这种行为,所以如果排除父节点,那么所有子节点也会被排除?

1 个答案:

答案 0 :(得分:0)

好。这是解决方案

在ApplicationController中:

before_filter do
    @main_menu = Page.where(active: true, show_in_main_menu: true).arrange(order: :position)

    def menu_ids(attributes, mids = [])
      attributes.map do |attribute, sub_attributes|
        if sub_attributes.empty?
          mids << attribute.id.to_s
        else
          mids << attribute.id.to_s
          menu_ids(sub_attributes, mids)
        end
      end
      mids
    end
    @menu_ids = menu_ids(@main_menu)
  end

在ApplicationHelper中:

def main_menu(attributes)
    attributes.map do |attribute, sub_attributes|
      if sub_attributes.empty?
        if @menu_ids.include?(attribute.parent_id.to_s)
          content_tag(:li) do
            link_to attribute.name.html_safe, page_path(attribute._id)
          end
        end
      else
        if attribute.parent_id == nil
          content_tag(:li, nil, class: "dropdown") do
            begin
              link_to( attribute.name.html_safe, page_path(attribute._id))+
              (icon('angle-double-right') if !attribute.is_root?)+
              content_tag(:ul, nil) do
                main_menu(sub_attributes)
              end
            end.html_safe
          end
        else
          if @menu_ids.include?(attribute.parent_id.to_s)
            content_tag(:li, nil, class: "dropdown") do
              begin
                link_to( attribute.name.html_safe, page_path(attribute._id))+
                (icon('angle-double-right') if !attribute.is_root?)+
                content_tag(:ul, nil) do
                  main_menu(sub_attributes)
                end
              end.html_safe
            end
          end
        end
      end
    end.join.html_safe
  end

它终于像我想要的那样工作