jeudi 20 octobre 2022

Join table if value is X or related table does not exist with X value

I have a users table and reporting_events table. reporting_event belongs to user. I used join on users table like.

   users.joins(:reporting_events).where(reporting_events: { name: sort_column } )

Here I get users with reporting event names as sort_column.

I want to list users if reporting_events name is sort_column or if user does't have a reporting_event with name sort_column.

I want to user order after this where clause like:

  users.joins(:reporting_events).where(reporting_events: { name: sort_column } ).group("users.id").order("count(reporting_events) #{sort_direction} nulls last")

The problem is that this returns only those users with reporting events with the sort_column name. I want to return all the users always, and to order them by count of reporting events with the name if the reporting_event exists.

Aucun commentaire:

Enregistrer un commentaire