LoginSignup
2
0

More than 1 year has passed since last update.

ゲストログイン機能 [Rails/LexicallyScopedActionFilter:]

Posted at

ゲストログインを実装時にRubocopでチェックすると、
Rails/LexicallyScopedActionFilter: update, destroy
このように指摘されました。

その際のコードは下記の通りです。

registrations_controller.rb

module Users
  class RegistrationsController < Devise::RegistrationsController
    before_action :ensure_normal_user, only: %i[update destroy]

    def ensure_normal_user
      redirect_to root_path, alert: "ゲストユーザーの更新・削除はできません。" if resource.email == "guest@example.com"
    end

                #〜〜〜〜略〜〜〜〜〜
end

https://www.rubydoc.info/gems/rubocop/0.58.0/RuboCop/Cop/Rails/LexicallyScopedActionFilter
こちらを参考に下記のように編集。

registrations_controller.rb
module Users
  class RegistrationsController < Devise::RegistrationsController
    before_action :ensure_normal_user, only: %i[update destroy]

    def update; end

    def destroy; end

    def ensure_normal_user
      redirect_to root_path, alert: "ゲストユーザーの更新・削除はできません。" if resource.email == "guest@example.com"
    end

                 #〜〜〜〜略〜〜〜〜
end

rubocop -aを実行すると指摘されることは無くなりました。

ターミナル
❯ rubocop -a
Inspecting 52 files
....................................................
52 files inspected, no offenses detected

しかし、ゲストログイン機能としては問題ありませんが通常のログインでアカウント編集ができなくなりました。

ターミナル
No template found for Users::RegistrationsController#update, rendering head :no_content
Completed 204 No Content in 32ms (ActiveRecord: 1.6ms | Allocations: 7284)

元々の親メソッドが機能していないということですね。
そこで super を使用し下記のように変更

registrations_controller.rb
module Users
  class RegistrationsController < Devise::RegistrationsController
    before_action :ensure_normal_user, only: %i[update destroy]

    def update
      super
      update_internal
    end

    def destroy
      super
      destroy_internal
    end

    def update_internal; end

    def destroy_internal; end

                 #〜〜〜〜略〜〜〜〜
end

これで rubocop -a で指摘されることもなく通常ログインでのアカウント編集も問題なく動きました。

2
0
1

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
0