Home > Back-end >  How to sort alphabetically with a form select using pluck.all
How to sort alphabetically with a form select using pluck.all

Time:12-12

I have a form and there's a drop down to choose dance styles however, this list is not in alphabetical order.

My form for the select is:

<%= f.label "Dance Style", class: "form-label" %>
<%= f.select :dance_styles_id_in, DanceStyle.all.pluck(:name, :id), { scope: :sorted, :include_blank => "All dance styles" }, { class: "form-select", id: "select-dancestyle", placeholder: "Any dance style", multiple: true } %>

I also tried:

<%= f.label "Dance Style", class: "form-label" %>
<%= f.select :dance_styles_id_in, DanceStyle.all.pluck(:name, :id).order(name: :asc), { :include_blank => "All dance styles" }, { class: "form-select", id: "select-dancestyle", placeholder: "Any dance style", multiple: true } %>

I tried to add the scope connected to my dance_style.rb model where I am sorting with the following but not 100% sure about syntax, but it works in the rails console:

scope :sorted, -> { DanceStyle.order(name: :asc) }

How would I pull this scope into my form? I feel I'm missing something simple and my Google searches haven't been helping...

CodePudding user response:

Your approach with the scope seems a good idea, as you can eventually re-use it in other places. You can simplify it a bit:

scope :sorted, -> { order(name: :asc) }

And then in your views:

<%= f.select :dance_styles_id_in, options_for_select(DanceStyle.sorted.pluck(:name, :id)), ... %>

CodePudding user response:

Can not order after pluck because pluck returns an array, and order using after ActiveRecord_Relation. So let's try to change:

DanceStyle.select(:name, :id).order(name: :asc)
  • Related