Grouped Collection选择按字母顺序排列的Rails

Sur*_*oza 4 ruby ruby-on-rails simple-form grouped-collection-select

我终于想出了如何使用本教程实现动态选择菜单.

一切正常,但是如何按名称组织下拉列表中的城市....

以下是我写的所有代码.(如果您需要任何进一步的信息,请告诉我)

新的铁路请帮助:)

VIEWS

<%= simple_form_for ([@book, @rating]) do |f| %>

  <div class="field">
    <%= f.collection_select :state_id, State.order(:name),  :id, :name, {:include_blank=> "Select a State"}, {:class=>'dropdown'} %>
  </div>


  ### I would like the order of the cities displayed in the drop down to be alphabetized 
  <div class="field">
    <%= f.grouped_collection_select :city_id, State.order(:name), :cities, :name, :id, :name, {:include_blank=> "Select a City"}, {:class=>'dropdown'} %>
  </div>        

<% end %>
Run Code Online (Sandbox Code Playgroud)

zea*_*soi 7

选项1:在City模型中,添加一个默认范围,指示按字母顺序返回城市:

# app/models/city.rb
default_scope :order => 'cities.name ASC'
Run Code Online (Sandbox Code Playgroud)

集合City对象将在默认情况下,可以按名称字母顺序返回英寸

选项2:模型中定义命名范围 ,State范围按字母顺序返回城市作为State对象的关联:

# app/models/state.rb
scope :cities_by_name, -> { cities.order(name: :asc) } # Rails 4

scope :cities_by_name, cities.order("name ASC") # Rails 3
Run Code Online (Sandbox Code Playgroud)

然后,将您的范围查询传递给您的grouped_collection帮助者:

f.grouped_collection_select :city_id, State.order(:name), :cities_by_name, :name, :id, :name, {:include_blank=> "Select a City"}, {:class=>'dropdown'}
Run Code Online (Sandbox Code Playgroud)


小智 5

使用Rails 4:

# app/models/city.rb
scope :ordered_name, -> { order(name: :asc) }

# app/models/state.rb
has_many :cities, -> { ordered_name }
Run Code Online (Sandbox Code Playgroud)