分组集合选择按字母顺序排列的 Rails [英] Grouped Collection Select Alphabetical Order Rails

查看:52
本文介绍了分组集合选择按字母顺序排列的 Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于知道如何使用 本教程实现动态选择菜单.

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

下面是我写的所有代码.(如果您需要更多信息,请告诉我)

Rails 新手请帮忙:)

视图

<%= simple_form_for ([@book, @rating]) do |f|%><div class="field"><%= f.collection_select :state_id, State.order(:name), :id, :name, {:include_blank=>"选择一个状态"}, {:class=>'dropdown'} %>

### 我希望下拉列表中显示的城市顺序按字母顺序排列<div class="field"><%= f.grouped_collection_select :city_id, State.order(:name), :cities, :name, :id, :name, {:include_blank=>"选择一个城市"}, {:class=>'dropdown'} %>

<%结束%>

解决方案

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

# app/models/city.rbdefault_scope :order =>'城市名称 ASC'

City 对象的集合将默认按名称的字母顺序返回.

选项 2:定义一个命名范围在你的 State 模型中,它以字母顺序返回城市作为 State 对象上的关联:

# app/models/state.rb范围:cities_by_name,->{ city.order(name: :asc) } # Rails 4scope :cities_by_name, city.order("name ASC") # Rails 3

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

f.grouped_collection_select :city_id, State.order(:name), :cities_by_name, :name, :id, :name, {:include_blank=>"选择一个城市"}, {:class=>'dropdown'}

I finally figured out how to implement Dynamic Select menus using this tutorial.

Everything works, But how does one organize the Cities in the Dropdown by Name....

Below is all of the code I've written. (Please let me know if you need any further information)

New to rails please help :)

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 %>

解决方案

Option 1: In your City model, add a default scope that directs cities to be returned in alphabetical order:

# app/models/city.rb
default_scope :order => 'cities.name ASC'

Collections of City objects will, by default, be returned in alphabetically by name.

Option 2: Define a named scope in your State model that returns cities in alphabetical order as an association on a State object:

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

scope :cities_by_name, cities.order("name ASC") # Rails 3

Then, pass your scoped query to your grouped_collection helper:

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

这篇关于分组集合选择按字母顺序排列的 Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆