【问题标题】:Rails group_by and sorting upon field in related modelRails group_by 和相关模型中的字段排序
【发布时间】:2016-08-11 10:28:38
【问题描述】:

我有一个属于 User_type 的用户。在 user_type 模型中,有一个名为 position 的字段来处理显示 user_types 及其用户时的默认排序。

不幸的是,这在使用 Ransack 搜索时不起作用,所以我需要从 User 模型中搜索并使用 group_by 根据它们的 user_type_id 对记录进行分组。

这很好用,但我需要一种方法来尊重 user_type 模型中定义的排序。这也是动态的,因此无法从用户模型中判断排序是什么。

因此,我认为我需要遍历 group_by 数组并手动进行排序。但我不知道从哪里开始。这是控制器方法:

  def index
    @q = User.ransack(params[:q])
    @users = @q.result(distinct: true).group_by &:user_type
  end

如何操作该数组以对相关模型中的字段进行排序?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    尝试将此行添加到Usertype模型

    default_scope order('position')

    【讨论】:

    • default_scope 在任何情况下都不是一个好主意。它可能会导致意外行为。最好创建作用域或使用纯order方法。
    • 这不起作用,因为没有从 UserType 进行查询。
    【解决方案2】:

    首先有n+1个查询问题。您没有将 user_types 表加入到 users 并且应用程序在 user_types 上调用 SELECT n 次,其中 n 是用户数 + 另一个 SELECT 调用以获取用户:

      ...
      UserType Load (0.2ms)  SELECT  "user_types".* FROM "user_types" WHERE "user_types"."id" = $1 LIMIT 1  [["id", 29]]
      UserType Load (0.2ms)  SELECT  "user_types".* FROM "user_types" WHERE "user_types"."id" = $1 LIMIT 1  [["id", 7]]
      ...
    

    所以您需要包含user_types 并通过user_types.position 订购:

    @q.result(distinct: true).includes(:user_type).order('user_types.position')
    

    这里有很多订购的例子:

    http://apidock.com/rails/ActiveRecord/QueryMethods/order

    您的案例(关联排序)也可用

    关于 n+1 查询的信息:

    What is SELECT N+1?

    【讨论】:

    • 好的,它确实有效,谢谢!我认为这不会尊重 user_type。还有一种方法可以对所述组中的用户进行排序吗?
    • @bo-oz 通过编辑您的问题提供有关组和用户之间关联的示例和问题。我将用解决方案扩展我的答案。
    猜你喜欢
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    相关资源
    最近更新 更多