0
0

More than 1 year has passed since last update.

devise を使いながら user 作成時に関連モデルをビルドする

Posted at

user モデルを作った
そして user モデルに has_oneuser_introduction モデルを作った

自分的には useruser_introduction をネストさせておいて
作成時にビルドさせる形にしたい。

しかし devise をつかっているのでどうしようとなった

開発環境

ruby 2.6.5
Ruby on Rails 5.2.5

このへん参考させていただいた。

どうするのかというと

useruser_introduction をネスト
②自分の環境に devise のコントローラーをインストール
③ユーザーの新規作成時だけ自分のコントローラーを通るようにルーティング
create アクションのあとに作成したユーザーに user_introduction をビルド

という流れ

以下具体的なフロー

① 

user.rb
has_one :user_introduction, dependent: :destroy
accepts_nested_attributes_for :user_introduction
user_introduce.rb
belongs_to :user

上記のように
useruser_introduction をネストする


コンソール上で

rails g devise:controller users 

をする

devise 本体のコントローラーが自分の環境にインストールされる

その中の
registrations_controller.rb

registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]
  before_action :configure_account_update_params, only: [:update]

  def new
    super
  end

  def create
    super
  end

  def edit
    super
  end

  def update
    super
  end

  def destroy
    super
  end

  def cancel
    super
  end

 protected

  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute])
  end

  def configure_account_update_params
    devise_parameter_sanitizer.permit(:account_update, keys: [:attribute])
  end

  def after_sign_up_path_for(resource)
    super(resource)
  end

  def after_inactive_sign_up_path_for(resource)
    super(resource)
  end
end

となるようにコメントアウト


ルーティングは

devise_for :users, controllers: {
    registrations: 'users/registrations'
  }

とする。
こうすることで新規登録のときだけ自分の環境を通るようになる


上記のコントローラー内を

 def create
    super
    resource.build_user_introduction
    resource.save
  end

とする
resource っていうのに新しく作られるユーザーがはいってるから
それに対して build_user_introduction してやると
中身は空だけど user_id が紐付いた user_introduction が作られる

追記

いろいろやったけどよくよく考えたら usercreate でコールバックさせればいいらしい
たしかに

0
0
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
0