0

I have a User that belongs to a User_type. In the user_type model, there's a field called position to handle the default sorting when displaying user_types and their users.

Unfortunataly this does not work when searching with Ransack, so I need to search from the User model and use group_by to group the records based on their user_type_id.

This works perfectly, but I need a way to respect the sorting that is defined in the user_type model. This is also dynamic, so there's no way of telling what the sorting is from the user model.

Therefor I think I need to loop through the group_by array and do the sorting manually. But I have no clue where to start. This is the controller method:

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

How do I manipulate that array to sort on a field that in the related model?

bo-oz
  • 2,842
  • 2
  • 24
  • 44

2 Answers2

0

Try to add this line to Usertype model

default_scope order('position')

0

First of all there is n+1 query problem. You are not joining user_types table to users and application calls SELECT on user_types n times where n is a number of Users + another one SELECT call to grab users:

  ...
  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]]
  ...

So you need to include user_types and order by user_types.position:

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

There are a lot of examples for ordering here:

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

Your case (Ordering on associations) is also available

Information about n+1 query:

What is SELECT N+1?

Community
  • 1
  • 1
Pavel Tkackenko
  • 963
  • 7
  • 20
  • Ok, it does work, thanks! I didn't think this would respect the user_type. Is there also a way to sort the users within said groups? – bo-oz Aug 11 '16 at 10:44
  • @bo-oz Provide example and problem about association between groups and users by editing your question. I will expand my answer with solution. – Pavel Tkackenko Aug 11 '16 at 10:50