Reputation: 912
I recently switched my project to postgres and it is messing up my select forms in small but annoying manner.
I have 2 select fields,
<%= f.collection_select :state, State.all, :value, :name, {include_blank: '- Select State -'} %>
<%= f.grouped_collection_select :area, State.all, :areas, :name, :value, :name, {include_blank: '- Select Area -'} %>
The first select field contains a bunch of States. The second select field contains a bunch of Areas/Districts grouped(optgroup) by States.
Using "seeds.rb", I inserted all the relevant data. Everything was inserted in alphabetical order. In SQLite3, the select results are all presented alphabetically. However, when i swapped over to Postgrsql, my :area select is now presenting its options in reverse alphabetical order which is terrible for user experience.
I have also tested the following scenario with the following query in the rails console:
State.find("Texas").areas
SQLite3 results:
[Area A, Area B, Area C]
Postgres results:
[Area C, Area B, Area A]
Is there any way i can get the same results as SQLite3 with Postgres while still using it with my "f.group_collection_select"?
Upvotes: 1
Views: 755
Reputation: 46
You can do this by defining a scope in your Area model
See : Grouped Collection Select Alphabetical Order Rails
Upvotes: 1
Reputation: 1032
use order clause on name or id whichever appropriate(I'd prefer name) with default scope for Area.
default_scope { order(:name :asc) }
Upvotes: 1
Reputation: 7744
You can specify the default order in the has_many
relationship.
class State < ActiveRecord::Base
has_many :areas, -> { order("areas.name ASC") }
end
Upvotes: 2