0

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.

vitaly107
  • 3
  • 2

2 Answers2

0

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.

anonymus_rex
  • 470
  • 4
  • 18
0

You can just create a constant array in your User model... add a field title to your User model

bundle exec rails g migration AddTitleToUser title:string
bundle exec rails db:migrate

modify your User class

class User < ApplicationRecord

  TITLES = %w[Mr Mrs Mx Dr Lord] # add more as necessary

add a selector on your form

<%= f.select :title, options_for_select(User::TITLES, f.object.title) %>
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53