Rails 应用中用户注册表单上英国个人头衔的下拉及其实现

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

我需要提供一个下拉列表以允许用户select他们在用户注册表单上的个人头衔(使用 Devise)。

我需要将该列表作为 closed/pre-defined 列表而不是用户填写的字段。

我是否需要创建一个单独的 model/DB table,例如 Title 来保留那些英国个人头衔(例如 Mr、Mrs 等)的列表,然后将它们与 User 模型相关联使用多对多关系和相应的中介 table 还是有其他选择或更好的解决方案?非常感谢。

由于您只需要一个静态列表,因此我建议为此使用 enum

首先将需要的字段添加到您的用户 table 如果您还没有这样做的话。 运行 rails g migration AddTitleToUsers title:integer,您的迁移应该如下所示:

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

在您的用户模型中:

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

在您的视图中,添加此内容以显示包含您的枚举值的下拉列表(假设 f 是您的用户表单):

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

检查 this enums tutorial and this related answer 如何将 select 输入与枚举一起使用。

您可以在您的用户模型中创建一个常量数组...向您的用户模型添加一个字段title

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

修改您的用户 class

class User < ApplicationRecord

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

在您的表单上添加一个选择器

<%= f.select :title, options_for_select(User::TITLES, f.object.title) %>