You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails的Devise Invitables中添加姓名与电话号码自定义字段

在Rails Devise Invitables中添加姓名与电话号码字段

1. 生成数据库迁移文件

先给用户表新增name和phone字段:

rails generate migration AddNameAndPhoneToUsers name:string phone:string

执行迁移生效:

rails db:migrate

2. 更新User模型

在app/models/user.rb中,将自定义字段加入Devise的邀请配置,并确保字段可批量赋值:

class User < ApplicationRecord
  devise :invitable, :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  # 指定邀请时需携带的自定义字段
  invitable_fields << :name << :phone
end

3. 修改发送邀请的表单

在自定义邀请页面(如app/views/users/invitation/new.html.erb)添加姓名、电话输入项:

<h2>邀请用户</h2>

<%= form_for(resource, as: resource_name, url: invitation_path(resource_name), html: { method: :post }) do |f| %>
  <%= devise_error_messages! %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>

  <!-- 自定义字段 -->
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>

  <div class="field">
    <%= f.label :phone %><br />
    <%= f.text_field :phone %>
  </div>

  <div class="actions">
    <%= f.submit "发送邀请" %>
  </div>
<% end %>

4. 修改接受邀请的表单

在接受邀请页面(app/views/users/invitation/edit.html.erb)添加对应字段,支持用户确认或修改:

<h2>接受邀请</h2>

<%= form_for(resource, as: resource_name, url: invitation_path(resource_name), html: { method: :put }) do |f| %>
  <%= devise_error_messages! %>
  <%= f.hidden_field :invitation_token %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name, value: resource.name %>
  </div>

  <div class="field">
    <%= f.label :phone %><br />
    <%= f.text_field :phone, value: resource.phone %>
  </div>

  <div class="field">
    <%= f.label :password %><br />
    <%= f.password_field :password, autocomplete: "new-password" %>
    <% if @minimum_password_length %>
      <br />
      <em><%= @minimum_password_length %> characters minimum</em>
    <% end %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
  </div>

  <div class="actions">
    <%= f.submit "接受邀请" %>
  </div>
<% end %>

5. 配置Strong Parameters

在app/controllers/application_controller.rb中添加参数过滤,允许自定义字段通过:

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    # 发送邀请时允许的字段
    devise_parameter_sanitizer.permit(:invite, keys: [:name, :phone])
    # 接受邀请时允许的字段
    devise_parameter_sanitizer.permit(:accept_invitation, keys: [:name, :phone, :password, :password_confirmation])
  end
end

6. 功能测试

启动服务器后,测试发送邀请流程,检查数据库中用户记录是否正确保存姓名、电话;再测试接受邀请的流程,确认字段能正常更新。

内容的提问来源于stack exchange,提问作者Neon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 04:05:11