LoginSignup
2
2

More than 3 years have passed since last update.

【rails】ユーザに紐づくデータをユーザ登録時に生成するための実装方法

Last updated at Posted at 2020-04-04

新規ユーザ登録時に、ユーザに紐づくデータを生成するよう実装した。
具体的には、新規ユーザが登録されたときに、外部キーとしてuser_idを持つFolderモデルとTagモデルのデータが生成されるようにした。

Gemfile

gem 'devise'

devise導入

bundle Install
rails g devise:install
rails g devise User

DeviseControllerのカスタマイズ

※認証ユーザーのモデルはUser

rails g devise:controllers users

# rails g devise:controllers [scope]

app/controllers/users 以下に次のコントローラが作成される。

・confirmations_controller.rb
・omniauth_callbacks_controller.rb
・passwords_controller.rb
・registrations_controller.rb
・sessions_controller.rb
・unlocks_controller.rb

ルーティング設定

registration_controller.rbのルーティング設定を行う。

config/routes.rb
Rails.application.routes.draw do
  # devise_for :users

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

registration_controller設定

newアクションのコメントアウトを外す。
createアクションにデータを生成する処理を記述する。

app/controllers/users/registrations_controller.rb

# frozen_string_literal: true

class Users::RegistrationsController < Devise::RegistrationsController
  # before_action :configure_sign_up_params, only: [:create]
  # before_action :configure_account_update_params, only: [:update]

  # GET /resource/sign_up
  def new
    super
  end

  # POST /resource
  def create
    super
    @default_folder = Folder.create( name: 'DefaultFolder', user_id: current_user.id )
    Tag.create( name: 'Temporary', user_id: current_user.id, folder_id: @default_folder.id )
  end


  # GET /resource/edit
  # def edit
  #   super
  # end
    ...

上記では、user_IDを外部キーとして持つFolderモデルとTagモデルのデータを生成している。
新規ユーザ登録により、登録したユーザーのuser_idを外部キーとして持つFolderモデルとTagモデルのデータが生成されるようになった。

参考文献

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