【问题标题】:awesome nested set order by令人敬畏的嵌套设置顺序
【发布时间】:2017-05-29 16:37:26
【问题描述】:

我正在为 ruby​​ on rails 使用awesome nested set 插件。我该如何按 :name 列或其他内容进行排序?

当前显示树状

A
- C
- B

我想要它

A
- B
- C

【问题讨论】:

  • 这已经更新为 :order_column ,感谢@askrynnikov 指出这一点

标签: ruby-on-rails treeview awesome-nested-set


【解决方案1】:

这样做会覆盖数据库排序:

@item.children.except(:order).order("your_sort_column")

例子:

organization.self_and_descendants.to_sql
=> "SELECT `organizations`.* FROM `organizations`  WHERE (`organizations`.`lft` >= 1 AND `organizations`.`lft` < 54) ORDER BY `organizations`.`lft`" 

organization.self_and_descendants.except(:order).order("organization_nm").to_sql
=> "SELECT `organizations`.* FROM `organizations`  WHERE (`organizations`.`lft` >= 1 AND `organizations`.`lft` < 54) ORDER BY organization_nm" 

【讨论】:

    【解决方案2】:

    不幸的是,现在不可能了。 在他们的课堂上写道“通过 lft 以外的其他列进行 oding 不起作用”(lib/awesome_nested_set.rb)

    【讨论】:

    • 2 年后,似乎仍然如此?
    • 3年后呢?
    • 对于它的价值,我能够用这个进行数据库排序:@item.children.except(:order).order("your_sort_column")
    • 在我看来,不执行位置行为就像创建没有踏板的自行车。你可以骑,但不是那么多:D 你用什么人进行标准网站导航? Rails 中似乎没有关于树行为和位置的决定。
    【解决方案3】:

    已经在awesome_nested_set实现了

    order_column:对哪一列进行排序,默认为 left_column_name。示例:acts_as_nested_set :order_column => :位置

    closure_tree

    如果您需要特定的顺序,请在 >migration 中向模型添加一个新的整数列:

    t.integer :sort_order
    

    在你的模型中:

    class OrderedTag < ActiveRecord::Base
      has_closure_tree order: 'sort_order'
    end
    

    【讨论】:

    • 是否可以只为子树触发一次这样的排序?
    【解决方案4】:

    我确认@kr00lix 所说的。 我绕过这个问题的方法:

    @item_children = @item.children
    @item_children = @item_children.sort_by!(&:your_sort_column)
    

    但我同意,为了避免无用的内存消耗,直接在SQL命令中设置顺序会更好。

    【讨论】:

      【解决方案5】:

      我可以在 Rails 中通过递归做到这一点:

      def add_self_and_children
        [self, children.sort_by{|e| e.name}.map{|c| c.add_self_and_children}].flatten
      end
      

      然后拨打Model.root.add_self_and_children

      但显然这涉及到一系列海量的数据库点击。

      因此,如果有人比我更了解 SQL 递归,并且想将其转换为纯 SQL,那就太神奇了!

      顺便说一句,由于某种原因,以下对数据库可能更友好的方法不起作用:

      def add_self_and_children
        [self, children.order(:name).map{|c| c.add_self_and_children}].flatten
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-09
        • 2021-03-06
        • 1970-01-01
        • 2019-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-14
        相关资源
        最近更新 更多