Ruby On Rails Retrieve Mysql Database Data 'a' Distinct 'b'
My database have a device reading list, columns are id ,device_id ,device_reading ,update_time How can I select all latest reading for each device? that means,I need sort data acco
Solution 1:
Supposing that model name is DeviceReading
DeviceReading.distinct(:device_id).order('update_time DESC').pluck(:device_reading)
You can use ASC
in place of DESC
if you want to sort by ascending order
Source: Distinct and pluck sort/order
EDIT: The distinct only works in rails 4 so if you are using rails 3 you should do something like this:
DeviceReading.select(:device_id).uniq.pluck(:device_reading)
However when I chain .order('update_time DESC')
in above I get mysterious error. I am trying to find solution. meanwhile I Hope this helps you.
Source: distinct undefined error
Solution 2:
This questions looks quite similar to the one below:
Select first row in each GROUP BY group?
In the case when no elegant solution can be found the Rails way, you can first figure out the correct sql and use find_by_sql
to retrieve the dataset.
Post a Comment for "Ruby On Rails Retrieve Mysql Database Data 'a' Distinct 'b'"