LoginSignup
2
0

More than 1 year has passed since last update.

【Rails】ログアウトしてる状態でホーム画面にアクセスしたら、ログイン画面に遷移してしまう問題とその解決方法

Last updated at Posted at 2022-03-07

経緯

  • アプリ制作時にログアウト画面を作ってない事に気付いて実装。しかしログアウト状態だとホーム画面にアクセスしたらログイン画面に遷移されてしまうので、解決を試みた。

開発環境

ruby 2.7.2
rails 6.0.4.6

原因はどこか

まずはアプリの動作を司ってるapplication_controller.rbに目星をつけた.
その時のコードは以下の通り

ruby application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

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

  protect_from_forgery with: :exception

に関してはCSRF対策(クロスサイトリクエストフォージェリ)であり、要はセキュリティ関係であるので今回は関係ない事が分かった。

次は

  before_action :configure_permitted_parameters, if: :devise_controller?

まずはbefore actionというのはあらゆるコンローラのフィルタリングするものである。
そしてあるゆるアクションより先に読み込まれるものである。
当然これを設定するならば、その読み込まれる定義自体もセットでないとダメ。
例えばbefore_actionがご飯の献立とするなら、そのご飯自体が作られないとおかしいよねって感じかな。つまりセットで初めて意味を成すもの。
下で記述されてる

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

がまさにそれ
ちなみにpermitはストロングパラメータ
これがないとダメですよっていうもの
これでいうとsign_up( つまり登録時は)、nameがないとダメですよって意味。
となると今回の問題とこれらは関係ないっぽい

別の角度から考える

逆にどうしたら非ログイン時にログイン画面を遷移させられるのか考えた。その為には以下の記述をすればいいらしい。でもapplication_controller.rb今回は別にそれないんだよな。そう思ってposts_controller.rbの方を見てみたらしっかり記述があった。これを消す

class PostsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_post, only: %i(show destroy)

新たなエラー

これを消したところ以下のエラー
スクリーンショット 2022-03-07 3.09.06.png
要は投稿とユーザーは結びつきがある設定のことを言われてる。
投稿ボタン押したらこうなるのは分かるけどルートに設定してるposts/indexを表示するだけなら関係なさそうだけどな。。

なぜこのエラーが出ているか

ポイント①ログイン状態ならきちんとposts/indexのルート画面を開く
ポイント②非ログインだとログイン画面に遷移されてしまう
ルーティングが影響しているという仮説を立てた

Rails.application.routes.draw do
  devise_for :users,
    controllers: { registrations: 'registrations' }
    root 'posts#index'
    get "users/index" => "users#index"
    get '/users/:id', to: 'users#show', as: 'user'

  resources :posts, only: %i(index new create show destroy) do
    resources :photos, only: %i(create)
    resources :likes, only: %i(create destroy)
    resources :comments, only: %i(create destroy)
  end
end

以下の記述のような,currentを使ったものいくつかあったが、それを消したらログアウト状態でも表示できた。
でもそれだとログイン状態との分岐が出来てないから、2つ記述すればいいのかな。記述増えるけど。後ほど追記します。

<% if post.user_id == current_user.id %>
2
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
2
0