0

I need to achieve something exactly similar to How to get list of values in GROUP_BY clause? but I need to use active record query interface in rails 4.2.1.

I have only gotten so far.

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

But this just returns an ActiveRecord::Relationobject with a single entry that has id and role.

How do I achieve that same with active record without having to pull in all the relationships and manually building such an object?

thebenman
  • 1,621
  • 14
  • 35

1 Answers1

1

Roles.where(id: 2) already returns the single record. You might instead start with users and join roles table doing something like this.

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

Or, if you have the model for user_roles, start with it since you nevertheless do not query anything from users.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160