【问题标题】:Grouped Collection Select Alphabetical Order Rails分组集合选择字母顺序 Rails
【发布时间】:2013-12-24 04:36:59
【问题描述】:

我终于想通了如何使用this tutorial 实现动态选择菜单。

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

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

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

【问题讨论】:

    标签: ruby-on-rails ruby simple-form grouped-collection-select


    【解决方案1】:

    选项 1:在您的 City 模型中,添加一个 default scope 以指示按字母顺序返回的城市:

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

    默认情况下,City 对象的集合将按名称的字母顺序返回。

    选项 2:在您的 State 模型中定义一个 named scope,该模型以字母顺序返回城市作为 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'}
    

    【讨论】:

    • 请问您实施的是哪种解决方案?
    • 我都试过了,它们都有效。但我实施了第一个。再次感谢
    • 第二个不再适用于 Rails 4。任何人都知道一种解决方法而不使范围成为函数?
    • 在 rails 3 中,对于范围示例,这给了我 -> #<0x007fddfa31de60>
    【解决方案2】:

    使用 Rails 4:

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

    【讨论】:

      【解决方案3】:

      如果使用 Rails 5.X,您可以使用 default_scope,其中的语法与 @zeantsoi 答案中的略有不同。

      default_scope { order('cities.name ASC') }
      
      

      【讨论】:

      • 注意:rails 5 弃用了旧答案中显示的 default_scope 语法。
      【解决方案4】:

      使用default_scope 订购City 型号怎么样?

      或者像这样创建一个State 范围:

      scope :ordered_cities, ->{ cities.order(:name) }
      

      而不是将您的选择更改为

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

      【讨论】:

        【解决方案5】:

        与此线程中的其他人一样,我在使用范围时遇到了问题。相反,我通过向 State 模型添加另一个关联来在 Rails 5 中实现这一点:

        has_many :cities_by_name, -&gt; { order(:name) }, class_name: 'City'

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-04-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-07
          • 1970-01-01
          • 2011-07-12
          • 1970-01-01
          相关资源
          最近更新 更多