在 rails 中分组为具有 activerecord 的列表

Grouping by into a list with activerecord in rails

我需要实现与How to get list of values in GROUP_BY clause?完全相似的东西,但我需要使用rails 4.2.1.

中的活动记录查询接口

我只了解了这么多。

Roles.where(id: 2)
        .select("user_roles.id, user_roles.role, GROUP_CONCAT(DISTINCT roles.group_id SEPARATOR ',') ")
        .group(:role)

但这只是 returns 一个具有单个条目的 ActiveRecord::Relation 对象,该条目具有 idrole

如何使用 Active Record 实现同样的效果,而不必拉入所有关系并手动构建这样的对象?

Roles.where(id: 2)已经returns单条记录。您可以改为从 users 开始并加入 roles table 做这样的事情。

User.
  joins(user_roles: :roles).
  where('roles.id = 2').
  select("user_roles.role, GROUP_CONCAT(DISTINCT roles.group_id SEPARATOR ',') ").
  group(:role)

或者,如果您有 user_roles 的模型,请从它开始,因为您仍然不会查询 users 的任何内容。