2
1

More than 3 years have passed since last update.

一覧表示(index)に特定のデータを表示させたいとき (current_userメソッド使用時)

Last updated at Posted at 2021-02-25

実装したかったこと

  • ログインしていなくても、indexページを表示させたかった
  • ログインしているユーザーのデータのみを一覧表示させたかった表示させたかった

ハマったこと

indexページにログインしているユーザーのデータのみを表示させようとした際に、current_userメソッドを理解できていなく、初歩的なミスに気付けなかった

BEFORE

accounts_controller
class AccountsController < ApplicationController
  before_action :authenticate_user!, except: :index

  def index
    @accounts = Account.where(user_id: current_user.id).order('created_at DESC')
  end
---省略---
end

AFTER

accounts_controller
class AccountsController < ApplicationController
  before_action :authenticate_user!, except: :index

  def index
    if user_signed_in?
      @accounts = Account.where(user_id: current_user.id).order('created_at DESC')
    end
  end
---省略---
end

みなさんなら、この違和感にすぐ気づけると思います。。。

勉強あるのみ。。。💪

解決策

if をつけることで、ログインしてから判定されるようにした🏄‍♂️

ログインできていない状態で、current_userメソッドが発動するようになっていたので、ここにifを入れることで、ログインしてから発動するようにできました💃

このミスに気付けずかなりハマりました、、、
しんどかった、、、

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