4

I want to get distinct records in rails. For that I see this Rails: how can I get unique values from column

But the issue is that by this solution I only get the Ids .

ViewsLog.uniq.pluck(:unit_id)
[24, 21, 23, 4, 16, 5, 7]

I want all columns of uniq unit_id

Community
  • 1
  • 1
Haseeb Ahmad
  • 7,914
  • 12
  • 55
  • 133
  • Distinct records based on what? What does your model look like? – shivam Dec 17 '15 at 07:38
  • My model is ["id", "user_id", "unit_id", "unit_type", "is_billed", "created_at", "updated_at", "user_credit", "deleted_at", "campaign_id"] and I want all distinct records on unit_id – Haseeb Ahmad Dec 17 '15 at 07:39

2 Answers2

9

You can use group; it gives you all distinct records:

 ViewsLog.group(:unit_id)
etdev
  • 524
  • 3
  • 12
Vishal JAIN
  • 1,940
  • 1
  • 11
  • 14
4

In rails to get distinct record can be used

ViewsLog.distinct(:unit_id)

If you are using postgres and have json type in a table then need to write like follow

ViewsLog.select('distinct on (views_logs.unit_id) views_logs.*')

Because postgres is not supporting to distinct if there is a json type filed in your table.

Vishal Zambre
  • 320
  • 1
  • 10
  • `distinct` is giving a error in `rails 3.2` from which version of rails this feature is supporting?? – Vishal JAIN Dec 21 '15 at 08:38
  • 1
    `ViewsLog.select('distinct on (views_logs.unit_id) views_logs.*')` Does not work in Rails 6.0.3.1 either – JotK. Jun 11 '20 at 10:50