@inrmnn

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

rails 画面遷移に伴うエラー

解決したいこと

コメント一覧画面から投稿詳細画面に戻ろうとするとエラーが出てしまいます

発生している問題・エラー

Showing /home/ec2-user/environment/reco_ani/app/views/public/favorites/_favorite.html.erb where line #1 raised:

undefined method `id' for nil:NilClass

       favorites.where(user_id: user.id).exists?
                                    ^^^
Extracted source (around line #12):
10
11
12
13
14
              
    
    def favorited_by?(user)
       favorites.where(user_id: user.id).exists?
    end
end


admin/posts/comment.html.erb

<div class="container">
    <div class="row">
        <div class="col-lg-10 offset-lg-1 mt-2">
           <%= link_to "投稿詳細へ戻る", admin_post_path(@post), class: "btn btn-primary p-3"  %>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-10 offset-lg-1 mt-3">
            <div class="border border-primary rounded bg-white">
                <h3 class="bg-primary text-white text-center py-3 mb-0">
                   コメント一覧
                </h3>
            
    
                <div class="row">
                    <div class="col-12">
                        <table class="table">
                                <thead class="table-secondary">
                                       <tr>
                                           <th style="width: 15%">投稿者</th>
                                           <th style="width: 60%">コメント</th>
                                           <th style="width: 15%">投稿日時</th>
                                           <th style="width: 10%"></th>
                                       </tr>
                                </thead>
                                <tbody>
                                    <!--コメントがない場合表示-->
                                     <% unless @comments.present? %>
                                        <tr>
                                            <td></td>
                                            <td>
                                             <h3 class="text-center">コメントはありません。</h3>
                                            </td>
                                            <td></td>
                                            <td></td>
                                        </tr>
                                    <% else %>
                                      <!--投稿に対してのコメントを表示-->
                                       <% @comments.each do |comment| %>
                                                <tr>
                                                    <td>
                                                       <%= link_to admin_user_path(@user), class: "text-dark" do %>    
                                                            <%= comment.user.name %>
                                                        <% end %>  
                                                    </td>
                                                    <td>
                                                       <%= comment.comment %>
                                                    </td>
                                                    <td>
                                                       <%= comment.created_at.strftime('%Y/%m/%d %H:%M') %>
                                                    </td>
                                                    <td>
                                                        <!--不適切なコメントなどを消す(管理者側でしか消せないようにしてあります-->
                                                        <%= link_to "削除", admin_post_comment_path(comment.post.id, comment.id), method: :delete, data: {confirm: "本当に削除しますか?"}, class:"btn btn-danger ml-1" %>
                                                    </td>
                                                </tr>
                                        <% end %>
                                     <% end %>    
                                </tbody>
                        </table>
                         <!--1ページ15個まで-->
                         <%= paginate @comments %>
                    </div>
                </div>
            </div>    
        </div>   
    </div>
</div>

### admin/posts/show.html.erb

<div class="container">
    <div class="row">
        <div class="col-lg-10 offset-lg-1 mt-5">
            <div class="border border-primary rounded bg-white">
                <h3 class="mb-3 bg-primary text-white text-center py-3">
                    投稿詳細
                </h3>
                <!--見づらいのでtableでの実装ができるとよい-->
                <!--投稿の詳細を表示-->
                <div class="row mt-5 justify-content-center">
                    <div class="col-12">
                        
                        <div class="row">
                            <div class="col-10 offset-1">
                              <h3 class="mt-3 text-border text-center mb-3">タイトル</h3>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-10 offset-1">
                              <h4 class="text-center mb-2"><%= @post.title %></h4>
                            </div>
                        </div>
                        
                        <!--新規投稿時に選んだジャンルを表示-->
                        <div class="row">
                            <div class="col-10 offset-1">
                              <h3 class="mt-3 text-border text-center mb-3">ジャンル</h3>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-10 offset-1">
                              <h4 class="text-center mb-2"><%= @post.genre.name %></h4>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-10 offset-1">
                              <h3 class="mt-3 text-border text-center mb-3">本文</h3>
                            </div>
                        </div>
                        
                         <div class="row">
                            <div class="col-10 offset-1">
                              <p class="text-center mb-5"><%= @post.body %></p>
                            </div>
                        </div>
                        <div class="row">
                           <div class="col-4 ml-5">
                               <h5 class="mb-4">コメント件数:<%= @post.comments.count %></h5>
                                <div class="text-left mb-5">
                                 <!--コメント一覧ページへ遷移-->
                                  <%= link_to "コメントを見る", comment_path, class:"btn btn-primary" %>
                                </div>
                           </div>
                           <div class="col-4 offset-2 text-right">
                               <h5>いいね数:<%= @post.favorites.count %></h5>  
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-10 offset-1">
                              <p class="text-right mb-5">
                                  <!--不適切な投稿を削除(投稿者吐けせるようになっています-->
                                <%= link_to "投稿を削除する", admin_post_path, method: :delete, data: {confirm: "本当に削除しますか?"}, class:"btn btn-danger ml-1" %>
                                </p>
                            </div>
                        </div>
                    </div>   
                </div>
            </div> 
        </div>
    </div>
</div>

admin/posts_controller

class Admin::PostsController < ApplicationController
  
  before_action :authenticate_admin!
  
  def index
     @posts = Post.page(params[:page])
  end

  def show
    @post = Post.find(params[:id])
    @user = @post.user
  end
  
  def destroy
    @post = Post.find(params[:id])
    @post.destroy
    flash[:notice] = "削除しました"
    # 投稿一覧画面へ遷移
    redirect_to admin_root_path
  end 
  
  def comments
     @post = Post.find(params[:id])
     @user = @post.user
     @comments = @post.comments.page(params[:page])
  end
  
end

post.rb

class Post < ApplicationRecord
    belongs_to :user
    belongs_to :genre
    has_many :comments, dependent: :destroy
    has_many :favorites, dependent: :destroy
    
    default_scope -> { order(updated_at: :desc) }
    
    validates_presence_of :title, :body
    
    def favorited_by?(user)
       favorites.where(user_id: user.id).exists?
    end
end

routes.rb

Rails.application.routes.draw do
  
  
   # ユーザー用
    # URL /users/sign_in ...
  devise_for :users, controllers: {
      registrations: "public/registrations",
      sessions: 'public/sessions'
    }
    
   # 管理者用
    # URL /admin/sign_in ...   サインインの場合はurlを打ち込んでください
  devise_for :admin, skip: [:registrations, :passwords] ,controllers: {
      sessions: "admin/sessions"
  }
  
  # 管理者用(adminから始まる)
  namespace :admin do
    resources :users, only: [:index, :show, :destroy]
   
    resources :genres, only: [:index, :create, :edit, :update, :destroy]
   
    resources :posts, only: [:show, :destroy] do
      
      # posts controllerだけだと削除がうまく行かないので分けています
      resources :comments, only: [:destroy]
      
    end
    
     # 投稿一覧画面がadminルートパスです
    root to: 'posts#index'
   
    get 'posts/comments/:id' => 'posts#comments' , as: 'comments'
   
  end
  
  # ユーザー用
  scope module: :public do
    resources :posts, only: [:new, :create, :index, :show, :edit, :update, :destroy] do
      # 検索結果表示用
       collection do
        get 'search'
       end
       resources :comments, only: [:create]
       resources :favorites, only: [:create, :destroy]
     end 
    get 'posts/comment/:id' => 'posts#comment' , as: 'comment'
    
    resources :users, only: [:show, :edit, :update] do
        member do
          get :favorites
        end
    end
    
    root to: 'homes#top'
  end
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

自分で試したこと

 def favorited_by?(user)
       favorites.where(user_id: user_id).exists?
    end

user.idだった部分をuser_idに変えると画面遷移のエラーは治ったのですがいいね機能が使えなくなってしまいました

0 likes

1Answer

気になることがいくつかあります。

コメント一覧画面から投稿詳細画面に戻ろうとするとエラーが出てしまいます

(1) エラーには_favorite.html.erb where line #1 raised:
出力がありますが、上記のパーシャルはどのように記述されていますか。

(2) post.rbにインスタンスメソッド def favorited_by?(user)
定義していますが、使用している箇所はどこでしょうか。

(3)定義する箇所などに検討の余地はありませんか。

post.rb
   def favorited_by?(user)
       favorites.where(user_id: user.id).exists?
   end

コード全容が不明なので恐縮ですが、
user.idをキーにしてfavoritesを取得する構図になっていますが、
そもそもこのメソッドをpost.rbに定義することが
質問者の方がイメージする設計と合っていますか?

0Like

Your answer might help someone💌