Home > Enterprise >  Rails Distinct with Condition
Rails Distinct with Condition

Time:06-03

I have four table in data which have repeated status but with different created_at (assuming it is on an associated model named "test")

Sample:

column 1: status_type : "test", created_at: "2019-08-14"

column 2: status_type : "test", created_at: "2020-20-14"

column 3: status_type : "integer", created_at: "2021-20-15"

column 4: status_type : "integer", created_at: "2022-22"15"

I want to get two data which is test and integer but i need the one who is the most updated or who is more recent based on their created_at. How to query this? Thank you

CodePudding user response:

You can do the following

Class.where(status_type: ['test', 'integer']).order('created_at').select('DISTINCT ON (status_type) *')
  • Related