Search code examples
rubyruby-on-rails-3devisehtml-selectgrouped-collection-select

grouped_collection_select, Devise and Rails 5.0 custom registration issue


I'm having having some issues with custom Devise registration in Rails 5. I have 3 models with the following AR associations

  • User (Devise)

    • belongs_to :chapter
  • Chapter

    • belongs_to :country
    • has_many :users
  • Country

    • has_many :chapters

I created a seed file for Chapter and Country and that's working fine, with their associations working perfectly. However, what I want to do is created a nested dropdown on the Sign Up page generated by Devise to choose the Chapter from the Country that they will belong to (and before anyone asks, this isn't a cult thing, it's for a social initiative project :P ). I'm able to add a custom field for username, so I know that my config/initializers/devise.rb and app/controllers/application_controller.rb is are configured correctly.

This is my grouped_collection_select:

<%= grouped_collection_select(resource, :chapter_id, Country.all, :chapters, :name, :id, :city) %>

which - bizarrely - produces an select tag like this:

<select name="#<User:0x007fb7686ba478>[chapter_id]" id="__User:0x007fb7686ba478_chapter_id" ></select

The name is all messed up and it's the reason it's not picking up the name when the form gets submitted, throwing the error 'Chapter must exist'. I've been on SO and Google all damn day trying to work out why and haven't got very far. It works fine when I do

<%= f.select :chapter_id, Chapter.pluck(:city, :id) %>

which creates...

<select name="user[chapter_id]" id="user_chapter_id" ></select

but I want a nested dropdown.

Any and all help is most welcome!


Solution

  • Maybe you'll try do it like this:

    grouped_collection_select(:user, :chapter_id, @countries, :chapters, :name, :id, :city)