ruby-on-rails-5filterrific

Setting scope for :sorted_by to select max date from join table


I am sure this is a simple syntax issue and I am taking a chance by asking the question but I just can't figure it out on my own. I have a functioning Filterrific :sorted_by selector, works great, sorts my Ticket records according to field values text and date types.

My Tickets table joins to a Comments table in a one-to-many relationship, and I am trying to sort a set of Ticket records by the newest update date from its associated Comment records.

Initially my solution was to add this to my scope:

when /*comment_date/
order("tickets.comments.updated_at #{direction}").includes(:comments).references(:comments)

The behavior is perplexing, my data is not being sorted across pagination, but perhaps coincidentally the records on a selected page are in order. I would love to post the backend SQL but work constraints do not allow it, so I hope I am not scolded or chastised for not providing enough evidence of my research.

Trying to find examples of Filterrific solutions is tough, after awhile I keep seeing the same posts on different websites. I have read every open and closed issue on GitHub, and the 79 or so tagged questions here on SO. It's so frustrating because I am sure there is a simple, logical solution but I can't see it!

As always, thank you for your time. I consider your attention a privilege, not a right, and I value any guidance.


Solution

  • Use joins instead of includes that way, the table is in your query.

    ...joins(:comments).references(:comments)

    Same as what @thesecretmaster mentioned. Just making a post so you can close this