双嵌套包括

时间:2018-11-10 21:17:15

标签: ruby-on-rails navigation sql-order-by rails-activerecord model-associations

我有一个存储在数据库中的导航结构。导航和导航项目有两种。

class Navigation < ApplicationRecord

  has_many :navigation_items

  scope :all_items, -> { 
    includes(navigation_items: [:translations, children: :translations])
      .order('navigation_items.position asc')
      .where(navigation_items: { parent_id: nil })
    }

end

class NavigationItem < ApplicationRecord

  has_many :children, class_name: "NavigationItem", foreign_key: "parent_id"
  belongs_to :parent, class_name: "NavigationItem", foreign_key: 'parent_id', optional: true
  belongs_to :navigation
end

我像这样在应用程序控制器中设置导航

def set_navigation
  @navigations = Navigation.all_items
  @navigation = []
  @footer_navigation = []
  @header_navigation = []

  if (main = @navigations.detect { |n| n.handle == "main" })
    @navigation = main.navigation_items
  end
  if (footer = @navigations.detect { |n| n.handle == "footer" })
    @footer_navigation = footer.navigation_items
  end
  if (header = @navigations.detect { |n| n.handle == "header" })
    @header_navigation = header.navigation_items
  end
end

然后我在布局中的每个Navigation_item中进行循环,并为孩子添加一个嵌套循环。

除一件事外,其他所有工具都工作正常。导航项均具有与它们相关的位置。父项以正确的顺序显示,但是子项没有遵循该顺序。有没有办法将子导航项的范围也按位置排序?

1 个答案:

答案 0 :(得分:0)

尝试

您可以使用default_scope或关联condition

class Navigation < ApplicationRecord
  # has_many :navigation_items, -> { where(parent_id: nil).order(position: :asc) }
  has_many :navigation_items, -> { where(parent_id: nil) }

  scope :all_items, -> { includes(navigation_items: [children: :children]) }
end

class NavigationItem < ApplicationRecord

  # has_many :children, -> { order position: :asc }, class_name: "NavigationItem", foreign_key: "parent_id"
  has_many :children, class_name: "NavigationItem", foreign_key: "parent_id"
  belongs_to :parent, class_name: "NavigationItem", foreign_key: 'parent_id', optional: true
  belongs_to :navigation

  default_scope -> { order position: :asc }
end