0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

姓と名を別々に入力させて、保存する前に結合する

Posted at

忘備録です。
Deviseでの新規登録
名前のフォームを姓と名に分けて入力させ、保存する前に結合させる

registrations/new.html.erb
  <%= f.label :firstName, "姓" %>
  <%= f.text_field :firstName, autofocus: true, required: true, class: 'form-control' %>
  <%= f.label :lastName, "名" %>
  <%= f.text_field :lastName, autofocus: true, required: true, class: 'form-control' %>
controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?
  
  protected
  # strong parameterで姓と名の属性(firstNameとlastName)をpermitする
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:firstName, :lastName])
  end
end
models/user.rb
  # 姓と名をDBに保存する前に結合
  before_create :create_name
  def create_name
    self.name = "#{firstName} #{lastName}"
  end
0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?