Grouped Collection Select Alphabetical Order Rails

前端 未结 5 1340
天命终不由人
天命终不由人 2021-01-03 05:27

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

Everything works, But how does one organize the Cities in t

相关标签:
5条回答
  • 2021-01-03 05:46

    If using Rails 5.X, you can use default_scope, in which the syntax is slightly different than in @zeantsoi answer.

    default_scope { order('cities.name ASC') }
    
    
    0 讨论(0)
  • 2021-01-03 05:52

    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'}
    
    0 讨论(0)
  • 2021-01-03 05:55

    Like others in this thread, I had issues getting this to work with scope. Instead I got this working in Rails 5 by adding another association to the State model:

    has_many :cities_by_name, -> { order(:name) }, class_name: 'City'

    0 讨论(0)
  • 2021-01-03 05:57

    How about using default_scope with ordering for City model?

    Or creating a State scope like that:

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

    and than changing your select to

    f.grouped_collection_select :city_id, State.order(:name), :ordered_cities, :name, :id, :name, {:include_blank=> "Select a City"}, {:class=>'dropdown'}
    
    0 讨论(0)
  • 2021-01-03 06:01

    With Rails 4 :

    # app/models/city.rb
    scope :ordered_name, -> { order(name: :asc) }
    
    # app/models/state.rb
    has_many :cities, -> { ordered_name }
    
    0 讨论(0)
提交回复
热议问题