【问题标题】:Instances of a model belonging to the same model Rails属于同一模型 Rails 的模型实例
【发布时间】:2017-04-20 08:34:06
【问题描述】:

我计划构建一个具有多层嵌套的复杂侧边栏菜单,用于显示指向不同类型页面的链接。因此模型

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]

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-5


    【解决方案1】:

    在menu_items 表中添加parent_id 并删除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
    

    【讨论】:

    • 我接受这个答案,因为外键设置正确并且里面有一个 has_many。
    【解决方案2】:

    构建一个树结构,其中每个项目都知道他的父项。

    $ 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)
    

    【讨论】:

    • 添加has_many :children ...... 关系也可能很有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 2015-02-03
    • 1970-01-01
    相关资源
    最近更新 更多