我终于明白了如何使用本教程.实现动态选择菜单
万事通,但如何组织城市的下拉名.
下面是我编写的所有代码。(如果您需要进一步的信息,请告诉我)
( rails新手请帮助:)
视图
<%= 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 %>发布于 2013-12-24 04:39:53
选项1:在City模型中,添加一个以字母顺序指示城市返回的默认范围:
# app/models/city.rb
default_scope :order => 'cities.name ASC'默认情况下,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然后,将作用域查询传递给您的grouped_collection助手:
f.grouped_collection_select :city_id, State.order(:name), :cities_by_name, :name, :id, :name, {:include_blank=> "Select a City"}, {:class=>'dropdown'}发布于 2014-09-03 09:01:32
使用Rails 4:
# app/models/city.rb
scope :ordered_name, -> { order(name: :asc) }
# app/models/state.rb
has_many :cities, -> { ordered_name }发布于 2019-07-31 11:37:32
如果使用Rails 5.X,则可以使用default_scope,其语法与@zeantsoi应答中的语法略有不同。
default_scope { order('cities.name ASC') }https://stackoverflow.com/questions/20754942
复制相似问题