kodamarisa / osinotameni_yasetai

0 stars 0 forks source link

ログイン動作について #52

Open kodamarisa opened 4 days ago

kodamarisa commented 4 days ago

Started GET "/profile" for ::1 at 2024-11-18 14:55:58 +0900 User Load (0.4ms) SELECT "users". FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 6], ["LIMIT", 1]] Processing by UsersController#profile as HTML Debug - Current Calendar ID in Session: 97 Debug - User: #<User id: 6, email: "paiza@demo.com", name: "パイザ", created_at: "2024-11-18 05:55:58.202771000 +0000", updated_at: "2024-11-18 05:55:58.202771000 +0000"> Calendar Load (0.4ms) SELECT "calendars". FROM "calendars" WHERE "calendars"."id" = $1 AND "calendars"."user_id" = $2 LIMIT $3 [["id", 97], ["user_id", 6], ["LIMIT", 1]] ↳ app/controllers/application_controller.rb:58:in `set_current_calendar' Debug - Current Calendar: #<Calendar id: 97, title: "Guest Calendar", image: nil, calendar_color: nil, calendar_type: nil, user_type: "User", user_id: 6, created_at: "2024-11-18 05:41:54.166543000 +0000", updated_at: "2024-11-18 05:55:58.209313000 +0000"> Rendering layout layouts/application.html.erb Rendering users/profile.html.erb within layouts/application Customize Load (0.6ms) SELECT "customizes".* FROM "customizes" WHERE "customizes"."user_id" = $1 LIMIT $2 [["user_id", 6], ["LIMIT", 1]] ↳ app/views/users/profile.html.erb:5 Rendered users/profile.html.erb within layouts/application (Duration: 1.8ms | Allocations: 957) [Webpacker] Everything's up-to-date. Nothing to do Rendered layouts/_header.html.erb (Duration: 0.1ms | Allocations: 39) Rendered layouts/_sidebar.html.erb (Duration: 0.1ms | Allocations: 125) Rendered layout layouts/application.html.erb (Duration: 9.2ms | Allocations: 12116) Completed 200 OK in 11ms (Views: 8.8ms | ActiveRecord: 1.0ms | Allocations: 13290)

Started GET "/calendars/97" for ::1 at 2024-11-18 14:56:01 +0900 Processing by CalendarsController#show as HTML Parameters: {"id"=>"97"} User Load (1.3ms) SELECT "users". FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 6], ["LIMIT", 1]] ↳ app/controllers/application_controller.rb:43:in `current_user_or_line_user' Debug - Current Calendar ID in Session: 97 Debug - User: #<User id: 6, email: "paiza@demo.com", name: "パイザ", created_at: "2024-11-18 05:55:58.202771000 +0000", updated_at: "2024-11-18 05:55:58.202771000 +0000"> Calendar Load (1.1ms) SELECT "calendars". FROM "calendars" WHERE "calendars"."id" = $1 AND "calendars"."user_id" = $2 LIMIT $3 [["id", 97], ["user_id", 6], ["LIMIT", 1]] ↳ app/controllers/application_controller.rb:58:in set_current_calendar' Debug - Current Calendar: #<Calendar id: 97, title: "Guest Calendar", image: nil, calendar_color: nil, calendar_type: nil, user_type: "User", user_id: 6, created_at: "2024-11-18 05:41:54.166543000 +0000", updated_at: "2024-11-18 05:55:58.209313000 +0000"> Calendar Load (1.0ms) SELECT "calendars".* FROM "calendars" WHERE "calendars"."id" = $1 LIMIT $2 [["id", 97], ["LIMIT", 1]] ↳ app/controllers/calendars_controller.rb:82:inset_calendar' CACHE Calendar Load (0.0ms) SELECT "calendars".* FROM "calendars" WHERE "calendars"."id" = $1 LIMIT $2 [["id", 97], ["LIMIT", 1]] ↳ app/controllers/calendars_controller.rb:44:in show' User Exists? (1.4ms) SELECT 1 AS one FROM "users" INNER JOIN "calendar_users" ON "users"."id" = "calendar_users"."user_id" WHERE "calendar_users"."calendar_id" = $1 AND "calendar_users"."user_type" = $2 AND "users"."id" = $3 LIMIT $4 [["calendar_id", 97], ["user_type", "User"], ["id", 6], ["LIMIT", 1]] ↳ app/controllers/calendars_controller.rb:117:inauthorized_to_view?' Redirected to http://localhost:3000/calendars Completed 302 Found in 20ms (ActiveRecord: 4.8ms | Allocations: 5859)

Started GET "/calendars" for ::1 at 2024-11-18 14:56:01 +0900 Processing by CalendarsController#index as HTML User Load (1.0ms) SELECT "users". FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 6], ["LIMIT", 1]] ↳ app/controllers/application_controller.rb:43:in `current_user_or_line_user' Debug - Current Calendar ID in Session: 97 Debug - User: #<User id: 6, email: "paiza@demo.com", name: "パイザ", created_at: "2024-11-18 05:55:58.202771000 +0000", updated_at: "2024-11-18 05:55:58.202771000 +0000"> Calendar Load (3.4ms) SELECT "calendars". FROM "calendars" WHERE "calendars"."id" = $1 AND "calendars"."user_id" = $2 LIMIT $3 [["id", 97], ["user_id", 6], ["LIMIT", 1]] ↳ app/controllers/application_controller.rb:58:in `set_current_calendar' Debug - Current Calendar: #<Calendar id: 97, title: "Guest Calendar", image: nil, calendar_color: nil, calendar_type: nil, user_type: "User", user_id: 6, created_at: "2024-11-18 05:41:54.166543000 +0000", updated_at: "2024-11-18 05:55:58.209313000 +0000"> Rendering layout layouts/application.html.erb Rendering calendars/index.html.erb within layouts/application Rendered /Users/kodamarisa/.rbenv/versions/3.1.4/lib/ruby/gems/3.1.0/gems/simple_calendar-3.0.4/app/views/simple_calendar/_month_calendar.html.erb (Duration: 2.7ms | Allocations: 5724) Rendered calendars/index.html.erb within layouts/application (Duration: 3.6ms | Allocations: 6291) [Webpacker] Everything's up-to-date. Nothing to do Rendered layouts/_header.html.erb (Duration: 0.1ms | Allocations: 38) Rendered layouts/_sidebar.html.erb (Duration: 0.1ms | Allocations: 128) Rendered layout layouts/application.html.erb (Duration: 12.0ms | Allocations: 17265) Completed 200 OK in 23ms (Views: 12.6ms | ActiveRecord: 4.4ms | Allocations: 19704)


- どの処理までうまく動いているのか
ユーザー登録は問題なく行えています。

- 該当のソースコード
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

def choose if user_signed_in? redirect_to user_profile_path end end

POST /resource

def create super do |user| if session[:guest_user_id] guest_user = GuestUser.find(session[:guest_user_id])

    # ユーザーに既存のカレンダーがあるかチェックし、なければゲストのカレンダーを引き継ぐ
    user_calendar = Calendar.find_by(user_id: user.id, user_type: 'User')
    guest_calendar = Calendar.find_by(user_id: guest_user.id, user_type: 'GuestUser')

    if user_calendar.nil? && guest_calendar
      # ゲストカレンダーをユーザーに関連付ける
      guest_calendar.update(user: user, user_type: 'User')
      session[:current_calendar_id] = guest_calendar.id
    else
      # 既存のカレンダーがあれば、ゲストカレンダーは削除
      guest_calendar&.destroy
    end

    # ゲストユーザーとそのセッション情報の削除
    guest_user.destroy
    session.delete(:guest_user_id)
  end
end

end

GET /resource/edit

def edit

super

end

PUT /resource

def update

super

end

DELETE /resource

def destroy

super

end

GET /resource/cancel

Forces the session data which is usually expired after sign

in to be expired now. This is useful if the user wants to

cancel oauth signing in/up in the middle of the process,

removing all OAuth session data.

def cancel

super

end

protected

If you have extra params to permit, append them to the sanitizer.

def configure_sign_up_params

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

end

If you have extra params to permit, append them to the sanitizer.

def configure_account_update_params

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

end

The path used after sign up.

def after_sign_up_path_for(resource) user_profile_path end

The path used after sign up for inactive accounts.

def after_inactive_sign_up_path_for(resource)

super(resource)

end

end

app/controllers/application_controller.rb

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

helper_method :current_line_user, :line_user_signed_in? helper_method :current_guest helper_method :current_user_or_line_user

protected

def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:name]) end

def set_current_line_user if session[:line_user_id].present? @current_line_user = LineUser.find_by(id: session[:line_user_id]) else @current_line_user = nil end end

def current_line_user @current_line_user end

def line_user_signed_in? @current_line_user.present? end

def authenticate_user_or_line_user! Rails.logger.debug "Debug - Current User: #{current_user.inspect}" Rails.logger.debug "Debug - Current Line User: #{current_line_user.inspect}" Rails.logger.debug "Debug - Current User or Line User: #{current_user_or_line_user.inspect}"

unless current_user_or_line_user
  redirect_to root_path, alert: 'You must be logged in to access this section.'
end

end

def current_user_or_line_user if user_signed_in? current_user elsif line_user_signed_in? current_line_user else nil end end

def set_current_calendar user = current_user_or_line_user || current_guest Rails.logger.debug "Debug - Current Calendar ID in Session: #{session[:current_calendar_id]}" Rails.logger.debug "Debug - User: #{user.inspect}"

if session[:current_calendar_id].present?
  @current_calendar = Calendar.find_by(id: session[:current_calendar_id], user_id: user.id)
else
  existing_calendar = Calendar.find_by(user_id: user.id, user_type: user.class.name)
  @current_calendar = existing_calendar || Calendar.create(title: "Default Calendar", user: user)
  session[:current_calendar_id] = @current_calendar.id
end

Rails.logger.debug "Debug - Current Calendar: #{@current_calendar.inspect}"

end

def current_calendar @current_calendar end

def current_guest if session[:guest_user_id] guest_user = GuestUser.find_by(id: session[:guest_user_id]) return guest_user if guest_user end

guest_user = GuestUser.create!
session[:guest_user_id] = guest_user.id
guest_user

rescue ActiveRecord::RecordNotFound => e Rails.logger.error "Guest user not found: #{e.message}" session.delete(:guest_user_id) guest_user = GuestUser.create! session[:guest_user_id] = guest_user.id guest_user end end


- エラーから考えられる原因
ユーザー登録時にカレンダーを新規作成してしまい、カレンダーの引き継ぎがうまくいっていない可能性があると思いました。

- 試したこと

user_calendar = Calendar.find_by(user_id: user.id, user_type: 'User')


を削除し、動作を確認してみましたが、うまく引き継げない状態です。
kenchasonakai commented 4 days ago

ユーザー登録時にカレンダーを新規作成してしまい、カレンダーの引き継ぎがうまくいっていない可能性があると思いました。

ログを出力したり、デバッグツールを使用してまず上記の推測が正しいのかの検証を行いましょう。 そのうえで変数や条件の実行結果を一つずつ確認してどこが自分の意図したものと違っているのかを探ってください。

それが出来てからコードを変更して修正する作業に移るとよいと思います

kodamarisa commented 2 days ago

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

  def choose
    if user_signed_in?
      redirect_to user_profile_path
    end
  end

  # POST /resource
  def create
    super do |user|
      if session[:guest_user_id]
        guest_user = GuestUser.find(session[:guest_user_id])
        Rails.logger.info "Guest user found: #{guest_user.id}"

        guest_calendar = Calendar.find_by(user_id: guest_user.id, user_type: 'GuestUser')

        # guest_calendarがnilでない場合に詳細をログに出力
        if guest_calendar
          Rails.logger.info "Found guest calendar: #{guest_calendar.inspect}"
          # 追加でゲストユーザーのカレンダー情報も表示
          Rails.logger.debug "Guest calendar details: #{guest_calendar.attributes}"
        else
          Rails.logger.warn "No guest calendar found for guest_user_id: #{guest_user.id}"
        end

        if guest_calendar #user_calendar.nil? &&を削除
          Rails.logger.debug "Guest calendar successfully linked to user: #{guest_calendar.id}"
          guest_calendar.update(user: user, user_type: 'User')
          session[:current_calendar_id] = guest_calendar.id
          Rails.logger.info "Guest calendar successfully linked to user. New calendar ID: #{guest_calendar.id}"
        else
          new_calendar = Calendar.create(user: user, user_type: 'User')
          session[:current_calendar_id] = new_calendar.id
          Rails.logger.info "New calendar created for user. Calendar ID: #{new_calendar.id}"
        end

        # ゲストユーザーとそのセッション情報の削除
        guest_user.destroy
        session.delete(:guest_user_id)
        Rails.logger.info "Guest user destroyed and session cleared."
      end
    end
  end

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

  # PUT /resource
  # def update
  #   super
  # end

  # DELETE /resource
  # def destroy
  #   super
  # end

  # GET /resource/cancel
  # Forces the session data which is usually expired after sign
  # in to be expired now. This is useful if the user wants to
  # cancel oauth signing in/up in the middle of the process,
  # removing all OAuth session data.
  # def cancel
  #   super
  # end

  # protected

  # If you have extra params to permit, append them to the sanitizer.
  # def configure_sign_up_params
  #   devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute])
  # end

  # If you have extra params to permit, append them to the sanitizer.
  # def configure_account_update_params
  #   devise_parameter_sanitizer.permit(:account_update, keys: [:attribute])
  # end

  # The path used after sign up.
  def after_sign_up_path_for(resource)
    user_profile_path
  end

  # The path used after sign up for inactive accounts.
  # def after_inactive_sign_up_path_for(resource)
  #   super(resource)
  # end
end

このようにログを出力するようにして、確認したところ、このログが出力されました。

Started POST "/users" for ::1 at 2024-11-20 17:20:35 +0900
Processing by Users::RegistrationsController#create as HTML
  Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"name"=>"パイザ3", "email"=>"paiza3@demo.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
  GuestUser Load (3.0ms)  SELECT "guest_users".* FROM "guest_users" WHERE "guest_users"."id" = $1 LIMIT $2  [["id", 41], ["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:74:in `current_guest'
Debug - Current Calendar ID in Session: 125
Debug - User: #<GuestUser id: 41, created_at: "2024-11-20 08:20:04.364119000 +0000", updated_at: "2024-11-20 08:20:04.364119000 +0000">
  Calendar Load (1.4ms)  SELECT "calendars".* FROM "calendars" WHERE "calendars"."id" = $1 AND "calendars"."user_id" = $2 LIMIT $3  [["id", 125], ["user_id", 41], ["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:58:in `set_current_calendar'
Debug - Current Calendar: #<Calendar id: 125, title: "い", image: nil, calendar_color: nil, calendar_type: nil, user_type: "GuestUser", user_id: 41, created_at: "2024-11-20 08:20:06.736070000 +0000", updated_at: "2024-11-20 08:20:06.736070000 +0000">
  TRANSACTION (0.9ms)  BEGIN
  ↳ app/controllers/users/registrations_controller.rb:20:in `create'
  User Exists? (0.9ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "paiza3@demo.com"], ["LIMIT", 1]]
  ↳ app/controllers/users/registrations_controller.rb:20:in `create'
  CACHE User Exists? (0.0ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "paiza3@demo.com"], ["LIMIT", 1]]
  ↳ app/controllers/users/registrations_controller.rb:20:in `create'
  User Create (0.8ms)  INSERT INTO "users" ("email", "encrypted_password", "name", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["email", "paiza3@demo.com"], ["encrypted_password", "$2a$12$UIZ/XRO9jNK2We5tbQTRv.IffsJi31fq155V71WdCKQ1zyFAsxdyq"], ["name", "パイザ3"], ["created_at", "2024-11-20 08:20:35.764356"], ["updated_at", "2024-11-20 08:20:35.764356"]]
  ↳ app/controllers/users/registrations_controller.rb:20:in `create'
  TRANSACTION (1.0ms)  COMMIT
  ↳ app/controllers/users/registrations_controller.rb:20:in `create'
  GuestUser Load (0.3ms)  SELECT "guest_users".* FROM "guest_users" WHERE "guest_users"."id" = $1 LIMIT $2  [["id", 41], ["LIMIT", 1]]
  ↳ app/controllers/users/registrations_controller.rb:22:in `block in create'
Guest user found: 41
  Calendar Load (0.6ms)  SELECT "calendars".* FROM "calendars" WHERE "calendars"."user_id" = $1 AND "calendars"."user_type" = $2 LIMIT $3  [["user_id", 41], ["user_type", "GuestUser"], ["LIMIT", 1]]
  ↳ app/controllers/users/registrations_controller.rb:25:in `block in create'
Found guest calendar: #<Calendar id: 124, title: "Guest Calendar", image: nil, calendar_color: nil, calendar_type: nil, user_type: "GuestUser", user_id: 41, created_at: "2024-11-20 08:20:04.367655000 +0000", updated_at: "2024-11-20 08:20:04.367655000 +0000">
Guest calendar details: {"id"=>124, "title"=>"Guest Calendar", "image"=>nil, "calendar_color"=>nil, "calendar_type"=>nil, "user_type"=>"GuestUser", "user_id"=>41, "created_at"=>Wed, 20 Nov 2024 08:20:04.367655000 UTC +00:00, "updated_at"=>Wed, 20 Nov 2024 08:20:04.367655000 UTC +00:00}
Guest calendar successfully linked to user: 124
  TRANSACTION (0.4ms)  BEGIN
  ↳ app/controllers/users/registrations_controller.rb:38:in `block in create'
  Calendar Update (0.9ms)  UPDATE "calendars" SET "user_type" = $1, "user_id" = $2, "updated_at" = $3 WHERE "calendars"."id" = $4  [["user_type", "User"], ["user_id", 14], ["updated_at", "2024-11-20 08:20:35.769030"], ["id", 124]]
  ↳ app/controllers/users/registrations_controller.rb:38:in `block in create'
  TRANSACTION (0.7ms)  COMMIT
  ↳ app/controllers/users/registrations_controller.rb:38:in `block in create'
Guest calendar successfully linked to user. New calendar ID: 124
  TRANSACTION (0.4ms)  BEGIN
  ↳ app/controllers/users/registrations_controller.rb:48:in `block in create'
  Calendar Load (0.6ms)  SELECT "calendars".* FROM "calendars" WHERE "calendars"."user_id" = $1 AND "calendars"."user_type" = $2 LIMIT $3  [["user_id", 41], ["user_type", "GuestUser"], ["LIMIT", 1]]
  ↳ app/controllers/users/registrations_controller.rb:48:in `block in create'
  CalendarUser Load (0.8ms)  SELECT "calendar_users".* FROM "calendar_users" WHERE "calendar_users"."calendar_id" = $1  [["calendar_id", 125]]
  ↳ app/controllers/users/registrations_controller.rb:48:in `block in create'
  CalendarUser Destroy (0.5ms)  DELETE FROM "calendar_users" WHERE "calendar_users"."id" = $1  [["id", 68]]
  ↳ app/controllers/users/registrations_controller.rb:48:in `block in create'
  Schedule Load (0.5ms)  SELECT "schedules".* FROM "schedules" WHERE "schedules"."calendar_id" = $1  [["calendar_id", 125]]
  ↳ app/controllers/users/registrations_controller.rb:48:in `block in create'
  Calendar Destroy (1.3ms)  DELETE FROM "calendars" WHERE "calendars"."id" = $1  [["id", 125]]
  ↳ app/controllers/users/registrations_controller.rb:48:in `block in create'
  GuestUser Destroy (0.4ms)  DELETE FROM "guest_users" WHERE "guest_users"."id" = $1  [["id", 41]]
  ↳ app/controllers/users/registrations_controller.rb:48:in `block in create'
  TRANSACTION (0.5ms)  COMMIT
  ↳ app/controllers/users/registrations_controller.rb:48:in `block in create'
Guest user destroyed and session cleared.
Redirected to http://localhost:3000/profile
Completed 303 See Other in 310ms (ActiveRecord: 16.0ms | Allocations: 19783)

これにより、ゲストカレンダーとは別のカレンダーが関連づけられてしまい、それがユーザーカレンダーに更新されてしまっている状態であることがわかりました。ですが、どうして別のカレンダーが関連づけられてしまっているのかわからない状態です。

kenchasonakai commented 2 days ago

これにより、ゲストカレンダーとは別のカレンダーが関連づけられてしまい、それがユーザーカレンダーに更新されてしまっている状態であることがわかりました。ですが、どうして別のカレンダーが関連づけられてしまっているのかわからない状態です。

一つ一つ処理を追って自分の頭の中で思っている正解の挙動と実際のコードで行われている処理の違いがどこにあるのかを確認してください。 コントローラーの全ての変数、コントローラーで受け取っているparams・sessionのすべてに対してどんなものが入っているのかを確認して意図したものと違うものがあった場合はViewから送られてきている値は正しいのか、コントローラーに書いているコードは自分の意図した通に動いているのか見てみましょう