Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

未ログインユーザーでもposts/indexとposts/showを見れるようにするにはどうすればいいでしょうか?

Q&A

Closed

未ログインユーザーでもposts/indexとposts/showを見れるように開発しようと思い、https://qiita.com/gogotakataka1234/items/c7d5c0b3d8953216259e
こちらの記事に書いてあった
before_action :authenticate_user, except: [:index, :show]
このコードをposts_controllerに記述したのですが、
エラーが発生してしまい理解ができず困っています
スクリーンショット 2022-10-25 15.50.09 1.png
このようなエラーが発生してしまいす。

def show
@post = Post.find_by(id: params[:id])
@user = @post.user
@likes_count = Like.where(post_id: @post.id).count
@post_detail = Post.find(params[:id])
unless ViewCount.find_by(user_id: @current_user.id, post_id:@post_detail.id)
@current_user.view_counts.create(post_id: @post_detail.id)
end
end

エラーになっているコードを丸々消すと次は
スクリーンショット 2022-10-25 15.54.35 1.png
このようなエラーになってしまいます。

できれば編集と削除、ユーザーの閲覧のカウント機能これらを消さないで全体に公開したいと考えています。
未ログインユーザーには編集と削除を非表示にして、閲覧数のカウントもログインユーザーのみのカウントのみでいいと考えています。

 なにかわかる方いましたら解決法を教えていただきたいです。
よろしくお願いします。

0 likes

1Answer

before_action :authenticate_user, except: [:index, :show]

authenticate_userを実行しないようにしているため、
@current_userがnilになっているのかと思います
authenticate_userの処理で@current_userが生成されます

@current_user&.idで指定するか、
if @current_user.present?で条件分岐してみたらどうでしょうか?

1Like

Comments

  1. @Kobayashi0620

    Questioner

    回答していただいてありがとうございます。
    提案いただいたものをどこに組めばいいのか教えていただけると助かります。
    勉強不足ですみません。

    二つ目のエラーは該当箇所に @current_user && を追加することで解決しました。(多分)
  2. >@current_user&.idで指定するか、
    >if @current_user.present?で条件分岐してみたらどうでしょうか?

    回答が不明確ですみません
    以下の2パターンで提案していました

    * @current_user&.idで指定するパターン
    ```
    unless ViewCount.find_by(user_id: @current_user&.id, post_id:@post_detail.id)
     @current_user.view_counts.create(post_id: @post_detail.id)
    end
    ```

    * if @current_user.present?で条件分岐
    ```
    if @current_user.present?
     unless ViewCount.find_by(user_id: @current_user&.id, post_id:@post_detail.id)
      @current_user.view_counts.create(post_id: @post_detail.id)
     end
    end
    ```
  3. @Kobayashi0620

    Questioner

    ありがとうございます!!

    >* if @current_user.present?で条件分岐
    の方を試したところ無事表示できました。

    親切に教えていただきありがとうございます!!

Your answer might help someone💌