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?
I think you want:
Topic.select('distinct on(name) id, name').order(:name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With