Search code examples
ruby-on-railsactiverecorddevise

Dropdown of UK personal titles on user registration form in Rails app and its implementation


I need to provide a dropdown to allow the user to select their personal title on user registration form (using Devise).

I need to have that list as a closed/pre-defined list rather than a field to be filled in by the user.

Do I need to create a separate model/DB table such as Title to keep a list of those UK personal titles (such as Mr, Mrs, etc) and then associate them with User model using many-to-many relationship and a corresponding intermediary table or is there some other option or better solution? Many thanks.


Solution

  • Since you need just an static list, I would recommend to use an enum for this.

    First add the needed field to your users table if you haven't done it yet. Run rails g migration AddTitleToUsers title:integer, and your migration should look like this:

    class AddTitleToUsers < ActiveRecord::Migration[5.1]
      def change
        add_column :users, :title, :integer
      end
    end
    

    In your User model:

    class User < ActiveRecord::Base
      enum title: [:mr, :mrs, :other]
    end
    

    And in your view, add this to display a dropdown with your enum values (assuming f is your User form):

    <%= f.select :title, User.titles.keys.map{ |t| [t.humanize, t] } %>
    

    Check this enums tutorial and this related answer of how to use select inputs with enums.