LoginSignup
10
16

More than 3 years have passed since last update.

ActiveRecord::RecordNotFound in

Posted at

今回ActiveRecord::RecordNotFound inのエラーで困ったのでメモです。

teratailで結果的に教えて頂き解決したのですがメモとして忘れないように書きたいと思います。
ほぼ質問した事のコピーとその続きです。

テーブル名
・novel_lists 
・users
多(novel_losts):1(users)の関係です。

novel_listsには
・title
・genre
・novel_keyword
・synopsis
・user_id  以上の5つのカラムがあります。

今回はusersのshow.html.erbファイルに書いていきます。

<% @novel_list.each do |novel_list| %>
            <div class="novellist_toptable">
                    <tbody>
                        <tr>
                            <td><%= link_to novel_list.title, novel_list_path(novel_list) %></td>
                            <td><%= novel_list.genre %></td>
                        </tr>
                        <tr>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <% end %>
このように記載し、novel_list_pathへとlinkをつなげています。
このlinkを踏んだ際に出るエラーとなります


まずはusersコントローラのshowアクションの部分です。
class UsersController < ApplicationController

  def show
    @user = User.find(params[:id])
    @novel_list = @user.novel_lists
    @followings = @user.followings.page(params[:page])
    @novel_lists = NovelList.all
    @favposts = current_user.favposts.page

エラー内容

ActiveRecord::RecordNotFound in NovelListsController#show
Couldn't find User with 'id'=4
Extracted source (around line #9):

  def show
    @user = User.find(params[:id])ここの部分にエラーが出ています。
    @novel_list = NovelList.find(params[:id])
    @novel_post = NovelPost.find(params[:id])
    @novel_posts = @novel_list.novel_posts

NovelListsControllerと出ているので・・・

novel_listsコントローラです。
class NovelListsController < ApplicationController

  def show
    @user = User.find(params[:id])
    @novel_list = NovelList.find(params[:id])
    @novel_post = NovelPost.find(params[:id])
    @novel_posts = @novel_list.novel_posts
  end

教えて頂いた解決策

エラー文に"Couldn't find User with 'id'=4"と書いてあります。意味としては、「id=4のユーザーはないよ」と言っています。なぜ、このようなことになっているかというと、novel_listsコントローラで@user = User.find(params[:id])としているからです。
今、id=4のノベルをクリックしているのでparams[:id]の値は4となります。なので、id=4のユーザーを探しに行った結果、id=4のユーザーは存在しないよと言っています。

そもそも、novel_listの中にユーザーidの情報が入っているので、そこでわざわざ@userとしなくていいと思います。Novel_listテーブルとUserテーブルをアソシエーションで結んでいれば、例えば、ビュー側で@novel_list.user.nameとすれば、ユーザーの情報は表示できると思います。

今までコントローラに書いて取得できるものであれば問題なく表示できるという認識でやってましたがここでとても重要な事を教わりました。
上記とてもわかりやすく、@user = User.find(params[:id])としてた事で、探して欲しいものとは違うものを取得する為に
コンピュータが動いていたとは予想外・・・でした。

こちら質問した際のURLです。内容はほぼ一緒です。

最後に@user削除後

作者:<%= link_to @novel_list.user.name, user_path(@novel_list) %>

作者の呼び出しに@user.nameを使ってたのエラーとなった訳ですが、
アドバイス通り、@novel_list.user.nameにする事で無事に呼び出す事が出来ました。

わかりやすく教えて頂けて感謝ですね。
今回困ったメモは以上です。

10
16
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
10
16