Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I select distinct records with ids from a database in Rails?

I am trying to select distinct records to populate a select tag and I need the ids from the query but when I write a query like this:

Topic.select(:name).distinct

It comes back with results that look like this:

#<ActiveRecord::Relation [#<Topic id: nil, name: "Ruby">, #<Topic id: nil, name: "Python">, #<Topic id: nil, name: "tingz">, #<Topic id: nil, name: "Javascript">, #<Topic id: nil, name: "Java">]>

And in order to get my select drop down to work properly I need the corresponding ids to be returned as well

This is the select tag that I am using in my view:

<%= select_tag :topic_search, options_from_collection_for_select(Topic.select(:name).distinct, :id, :name), placeholder: "Select topic" %>

Does anyone have any idea of what the best way of doing something like this is?

like image 688
Jamaal Avatar asked Feb 03 '26 07:02

Jamaal


1 Answers

I think you want:

Topic.select('distinct on(name) id, name').order(:name)
like image 141
maniek Avatar answered Feb 04 '26 21:02

maniek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!