-1

In the following table of data:

enter image description here

I am trying to select from this table the records that are distinct based off of the columns itemable_id, itemable_type, and user_id. I also want the records sorted by last_viewed_at. In rails, I have been able to get the records to be distinct, but every way I try always gets record ID 1 instead of 4 for ThingType1 that has itemable_id 32. Essentially, the record set iI'm trying to end up with is one with rows with IDs 4, 3, and 2. How can i do this efficiently?

ryanpitts1
  • 862
  • 1
  • 16
  • 33

1 Answers1

0

You can use group to get a group of distinct records and then order them by asc or desc -

UserItemView.select(:user_id, : itemable_type, :itemable_id).group(:user_id, : itemable_type, :itemable_id).order(last_viewed_at: :desc)
Gautam
  • 1,754
  • 1
  • 14
  • 22