LoginSignup
0
0

More than 3 years have passed since last update.

railsのいいね機能の変数エラーについて

Posted at

前提・実現したいこと

railsを使ってwebアプリケーションを作成中です。
自分がいいねをつけた投稿を全投稿の中からソートして画面に表示したいです。
しかし、postの部分にエラーが出てしまいました。
その実

発生している問題・エラーメッセージ

Showing C:/Users/user/dome/app/views/users/likesline.html.erb where line #26 raised:

undefined method `id' for nil:NilClass
   <% post = Post.find_by(id: like.post_id) %>
      <div class="users-index-item">
<%# ここから=========%>
        <%= link_to("/posts/#{post.id}") do %>
<%# ここまで=========%>
        <div class="user-left">
          <img src="<%= "/post_images/#{post.image_name}" %>">
        </div>

該当コード

likesline.html.erb

<div class="users-contents">
      <div class="users-index-item-sorce">
      <% @like.each do |like| %>
      <% post = Post.find_by(id: like.post_id) %>
      <div class="users-index-item">
        <%= link_to("/posts/#{post.id}") do %>
        <div class="user-left">
          <img src="<%= "/post_images/#{post.image_name}" %>">
        </div>
        <div class="post-right">
            <div class="post-right-link">
          <%= post.title %>
        </div>
      </div>
      <%end%>
  </div>
    <% end %>
</div>
</div>

users_controller.erb

def likesline
    @user = User.find_by(id: params[:id])
    @like = Like.where(user_id: @user.id)
  end

DB(SQLite)

users

id name email created_at updated_at image_name password
10 たんぽぽ tanpopo@gmail.com 2020-09-03 2020-09-14 10.jpg tanpopo
12 kosumosu kosumosu@gmail.com 2020-09-19 2020-09-19 12.jpg kosumosu

posts

id content created_at updated_at user_id image_name title
46 contents1 2020-09-19 2020-09-19 10 46.jpg title1
47 dfsdfsdf 2020-09-19 2020-09-19 10 47.jpg df

likes

id user_id post_id created_at updated_at
1 10 26 2020-09-04 03:57:42.503803 2020-09-04 03:57:42.503803
3 10 31 2020-09-18 12:28:35.206818 2020-09-18 12:28:35.206818
5 10 32 2020-09-19 02:27:20.465790 2020-09-19 02:27:20.465790
7 10 36 2020-09-19 06:27:53.983748 2020-09-19 06:27:53.983748
9 10 47 2020-09-19 10:50:58.208238 2020-09-19 10:50:58.208238
10 10 46 2020-09-20 07:30:15.554143 2020-09-20 07:30:15.554143

問題点

posts.idとlikes.post_idの間に共通して存在しないカラムが存在していること。
よって、likesテーブルの中からid: 1,3,5,7をコンソールを使ってdestroyを行いました。

likes

**id**  **user_id** **post_id** **created_at**  **updated_at**

9   10  47  2020-09-19 10:50:58.208238  2020-09-19 10:50:58.208238
10  10  46  2020-09-20 07:30:15.554143  2020-09-20 07:30:15.554143

すると、エラーが解消され無事にお気にいり登録されている投稿が表示できるようになりました。

回答してくれた方:tky_7201さん(teratailのurl:https://teratail.com/users/tky_7201#reply)

0
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
0
0