Home>

I am creating a posting application with Ruby on Rails.
I want to be able to display the posting screen list even when logging out.

When i am logged in after implementing the Like function, the post list screen is displayed, but if you log out and press the link on the post list screen, an error will occur.

NoMethodError in Tweets#index
 undefined method `already_favorited?' for nil:NilClass
Applicable source code
#Posting list screen code
.TweetMain
  .TweetMain__form
    [email protected] do |tweet|
      .TweetMain__menu
        .TweetMain__body
          = link_to user_path(tweet.user) do
            = attachment_image_tag tweet.user, :profile_image, fallback: "no-image.png", class: "Tweetshow__image"
          .TweetMain__body__name
            = link_to user_path(tweet.user), class: "TweetMain__body__Name" do
              = tweet.user.username
          .TweetMain__body__date
            = tweet.updated_at.strftime("%Y-%m-%d %H:%M")
        .TweetMain__title
          = link_to tweet_path(tweet), class: "TweetMain__Title" do
            = tweet.title
          .TweetMain__favorite
            -if current_user.already_favorited?(tweet) ← error is displayed here
              = link_to tweet_favorites_path(tweet), method: :delete, class: "Favorite" do
                = icon('fas','heart')
            -else
              = link_to tweet_favorites_path(tweet), method: :post, class: "Favorite" do
                = icon('far','heart')
            = tweet.favorites.count
class TweetsController
class User
class Tweet
What I tried

I thought that the cause was already_favorited?(tweet), so I made the same description in tweet.rb.
Didn't solve it.

  • Answer # 1

    -if current_user.already_favorited?(tweet) ← error is displayed here

    current_user is nil.

    before_action :authenticate_user!, except: [:index]


    Probably because authenticate excludes authenticate.

Related articles