Rob Rob - 2 years ago 66
Ruby Question

how to add uniqueness on a .where call in rails

I cant find this in the docs and searching for it only shows results for adding uniqueness in the model.

How can I add uniqueness to a

call. I want to have the below command not grab
with the same

last_updated_items = CategoryItemValue.where(guide_id: :desc).limit(5)

So the command grabs 5 of the most recently updated
without getting 5 of them with the same
. if the
is the same as another most recently updated it skips it and adds the next most recently updated to the 5 results returned.


doing this using the
method and using
still gives duplicate
for some reason :desc).limit(5).pluck(:category_item_id, :updated_at)

[[6, Wed, 11 May 2016 10:24:39 UTC +00:00], [3, Wed, 11 May 2016 10:21:20 UTC +00:00], [3, Wed, 11 May 2016 10:20:43 UTC +00:00], [6, Wed, 11 May 2016 09:14:14 UTC +00:00], [5, Wed, 11 May 2016 09:14:04 UTC +00:00]]

notice the second and third array values both have 3 at the start. (plus im not sure if the comma after the day i the date time is going to effect pulling these values from the array)

Answer Source

Try something like this:, "MIN(updated_at) as updated_at").distinct.where(guide_id: @guide_id).group(:category_item_id).order(updated_at: :desc).limit(5)

Both of these group the results set by category_item_id, and should return one record for each category item, with the oldest (MIN) value for updated_at of that category item. The get the newest updated records, use MAX instead of MIN.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download