【问题标题】:trails trying to build a menu, need some assistance on the polymorphic association尝试构建菜单的路径,在多态关联方面需要一些帮助
【发布时间】:2017-10-09 14:13:53
【问题描述】:

我正在尝试为 CMS 构建一个菜单,在其中,您有顶级部分(由不属于另一个部分确定),其中包含更多部分或 navigation_items 的列表。

我无法将它们全部连接起来。

我有以下型号:

section.rb:

class Section < ActiveRecord::Base
  belongs_to :section, polymorphic: true
  has_many :navigation_items
end

navigation_item.rb:

class NavigationItem < ActiveRecord::Base
  belongs_to :section
end

能否按照我期望的那样连接所有设备?

【问题讨论】:

  • 你的问题是什么?
  • I'm having trouble getting it all connected。我认为这是不言而喻的。

标签: ruby ruby-on-rails-4 activerecord polymorphic-associations


【解决方案1】:

好的,所以我想通了,

我需要做一个迁移:

def change
    change_table :sections do |t|
      t.references :items, polymorphic: true, index: true, on_delete: :nullify, on_update: :cascade
      t.references :section, index: true, on_delete: :nullify, on_update: :cascade
    end
end

然后为类做:

class Section < ActiveRecord::Base
  belongs_to :items, polymorphic: true
  has_many :navigation_items, as: :items
  has_many :sections, as: :items
end

class NavigationItem < ActiveRecord::Base
  belongs_to :items, polymorphic: true
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    相关资源
    最近更新 更多