2017-04-20 63 views
1

我已经计划构建一个复杂的边栏菜单,其中包含多层嵌套,它显示指向不同类型页面的链接。因此,这个模型属于同一模型的模型的实例Rails

class MenuItem < ApplicationRecord 
    belongs_to :linkable, polymorphic: true 
end 

目前,它这样表示:

  • 链接1
  • 链接2
  • 链接3

现在,推出一种次级链接我会喜欢留在相同的模型,但看到的结果为:

  • 链接1
    • 链接一个
    • 链路B
  • 链路2
    • 路段C
  • 链路3

我不想再创建一个模型或继承,所以我最初的计划是通过添加更多的字段添加到MenuItem模型做到这一点:

is_subpage:boolean 
show_under:integer 

这样的方式来获得第二层和遍历它,我需要做的是这样的:

MenuItem.where(subpage: true, show_under: self.id) 

但也许有更好的方法来建立的关系?像

belongs_to :self, as: :subpage 

类这将让我做

MenuItem.subpages => [1, 2, 3] 

回答

3

添加PARENT_ID在menu_items表&删除is_sub_page & show_under领域

class MenuItem < ApplicationRecord 
    belongs_to :parent, :class_name => 'MenuItem' 
    has_many :children, :class_name => 'MenuItem', :foreign_key => :parent_id 
end 
+0

我接受这个答案,因为外键正确设置,并且has_many在其中。 –

1

建立一个树形结构,每个项目都知道他的父母。

$ rails g model MenuItem title:string menu_item_id:integer 

# models/menu_item.rb 
class MenuItem < ApplicationRecord 
    belongs_to :parent, class_name: 'MenuItem', foreign_key: 'menu_item_id' 

    # items without parent are the top-level menu items 
    scope :main_items, -> { where(parent: nil) } 
end 

查询儿童项目如下:

menu_item = MenuItem.find .. 
children = MenuItem.where(parent: menu_item) 
+1

这可能是有用的添加'的has_many:儿童......也有关系。 – Santhosh

相关问题