Reputation: 159
I have a model Program containing fields program_title, department_id and date. I have inserted two rows having same program title and date but different department_id.
Insert into programs(program_title,date,department_id) Values ("prog1","4/2/2017","1");
Insert into programs(program_title,date,department_id) Values ("prog1","4/2/2017","2");
Now I want to return rows which will be distinct by program_title whatever be the department_id. I have tried,
@event_contents=Program.select(:id,:date,:program_title).distinct(:program_title)
But still it returns both the rows. Any help is appreciated.
Upvotes: 2
Views: 93
Reputation: 727
Try this
Program.all.distinct(:program_title).pluck( :id,:program_title,:date)
It will return data as array of elements though
Hope it helps
Upvotes: 0
Reputation: 8787
SQL can only collapse rows where all values are the same when using DISTINCT
. Because you are selecting id
, which is different for every record, the rows are not distinct. E.g.:
---------------------------------
| id | program_title | date |
---------------------------------
| 1 | prog1 | 4/2/2017 |
| 2 | prog1 | 4/2/2017 |
---------------------------------
You'll need to exclude the id
from your #select
for it to work:
Program.select(:date, :program_title).distinct
Upvotes: 2