1

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"?

Tikiboy
  • 892
  • 10
  • 20

3 Answers3

2

You can specify the default order in the has_many relationship.

class State < ActiveRecord::Base
  has_many :areas, -> { order("areas.name ASC") }
end
SHS
  • 7,651
  • 3
  • 18
  • 28
  • God sent! I was trying to use it but didnt really know the right syntax. The rails guide doesnt provide the syntax. Where can u find more detailed explanation for these things? I was trying -> { order "'name' ASC" } on the belongs_to association. :( – Tikiboy Feb 13 '15 at 15:28
  • "Examples" section: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many – SHS Feb 13 '15 at 17:56
1

use order clause on name or id whichever appropriate(I'd prefer name) with default scope for Area.

default_scope { order(:name :asc) }
Abubakar
  • 1,022
  • 10
  • 20
1

You can do this by defining a scope in your Area model

See : Grouped Collection Select Alphabetical Order Rails

Community
  • 1
  • 1
Max
  • 46
  • 4