[英]How to sort alphabetically with a form select using pluck.all
我有一個表格,有一個下拉菜單可以選擇舞蹈 styles 但是,這個列表不是按字母順序排列的。
我的 select 表格是:
<%= 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 } %>
我也試過:
<%= 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 } %>
我嘗試添加連接到我的dance_style.rb
model 的 scope,我在其中使用以下但不是 100% 確定的語法進行排序,但它在 Rails 控制台中有效:
scope :sorted, -> { DanceStyle.order(name: :asc) }
我如何將這個 scope 拉到我的表格中? 我覺得我錯過了一些簡單的東西,我的谷歌搜索沒有幫助......
您使用 scope 的方法似乎是個好主意,因為您最終可以在其他地方重新使用它。 你可以稍微簡化一下:
scope :sorted, -> { order(name: :asc) }
然后在你看來:
<%= f.select :dance_styles_id_in, options_for_select(DanceStyle.sorted.pluck(:name, :id)), ... %>
不能在pluck
之后order
,因為pluck
返回一個array
,並且在ActiveRecord_Relation
之后使用order
。 因此,讓我們嘗試更改:
DanceStyle.select(:name, :id).order(name: :asc)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.