我有一个存储在数据库中的导航结构。有两种型号"导航"one_answers"导航项"。
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,并为子项嵌套循环。
除了一件事,一切都很顺利。导航项都有一个绑定到它们的位置。父项按正确的顺序显示,但子项不遵守该顺序。有没有办法也将儿童导航项目按位置排序?
尝试这个
可以使用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