3
0

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.

device ユーザーcreateと同時に別のモデルもcreate

Posted at

railsで新規ユーザー登録をする時、同時に、サーチモデルも作成されるようにしましたので、説明します。

やり方)
deviceのcontrollerをカスタマイズする。

詳細)
まず、ルーティングを設定。
以下を追加。

routes.rb
  devise_for :users,controllers: { registrations: "users/registrations",}

次はcontrollarをカスタマイズ

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
    @user = User.new
    @search_height = SearchHeight.new
  end

  def create
    @user = User.new(configure_sign_up_params)
    if @user.save
      SearchHeight.create(min_height: 0, max_height: 200, user_id: @user.id)
      sign_in(@user)
      redirect_to new_profile_user_path(@user)
    end
  end

  protected

  def configure_sign_up_params
    params.permit(:email, :password, :password_confirmation, :sex)
  end

  def after_sign_up_path_for(resource)
    new_profile_user_path(current_user)
  end

  def after_inactive_sign_up_path_for(resource)
    new_profile_user_path(current_user)
  end
end

ユーザーがcreateされたら、SearchHeightもcreateされる。

ここで、ポイント!
sign_in(@user)が大事。これがないとsessionが付かないので、ログインしたことにならない。

そして、viewの設定

new.html.slim
  = form_tag @user, url: user_registration_path do
    = devise_error_messages!
    .devise-registration__textarea
      = select_tag :sex, options_for_select({ "男性": "男", "女性": "女"}), { prompt: "性別", class: "devise_registration_select"}
      = email_field_tag :email,"", placeholder: " メールアドレス"
      = password_field_tag :password,"", autocomplete: "off", placeholder: " パスワード(英数字4文字以上)"
      %p.devise-i (確認)
      = password_field_tag :password_confirmation,"", autocomplete: "off", placeholder: " もう一度パスワードを入力して下さい", class: "devise_registration_area_confirmation"
      = submit_tag "登録", class: 'registration__create'

今回は、form_tagでやった。
特に意味はない。

これで同時に作成できるはず。

以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?