5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rails whereメソッドとfindメソッドの違い メモ

Last updated at Posted at 2019-07-23

はじめに

railsのエラーを解く問題で解けなかった問題を復習のため
記述してます。

問題内容

以下のエラーがでないようにコードを修正する。

NoMethodError in Products#show
<header class="header header--section">
 <h2 class="text-middle">
  <i class="icon-movie color-gray-light"></i><%= @product.title %>
 </h2>
</header>

問題を解くときに考えたこと

NoMethodError in Products#showとあり
<%= @product.title %>
に赤線が引かれていたので
@productに対してのshowアクションが何かうまく行ってないのでは?と考えた。

そこでproductのコントローラーファイルを確認してみる。

def show
    @product = Product.where(params[:id]) 
end

whereメソッドを使って対象のidの情報を@productに代入しているので大丈夫そう。
whereメソッドは引数に取得してきたい条件をもたせ、それに該当するレコードを配列として持ってくるメソッドだから、ここでは
対象のidを条件とし持ってくる様に指示しているから問題はないのでは?

解答確認

before
@product = Product.where(params[:id])

after
@product = Product.find(params[:id])

解答確認の感想

解答を確認して、修正箇所の着眼点は良かった。
けどなんでfind?
findの使い方はわかるけど、whereでもいいんじゃないの?
コード的には問題ないじゃん!

復習

まずfindメソッドとwhereメソッドの違いを確認にすることにしました。

すると
@tsuchinoko_runの記事で今回の問題について納得ができました。ありがとうございます。

find、find_by、whereの違い
https://qiita.com/tsuchinoko_run/items/f3926caaec461cfa1ca3

学習後の認識

・findメソッドはidを引数として持たせる。id以外での検索はできない。

・whereメソッドはid以外を引数として持たせる。idでの検索はできない。

そのため今回の問題はwhereメソッドの条件にid
をもたせていたため、DBの情報を持ってくることができず、
@product.titleを表示ができなく
エラーが発生していた。

まとめが非常に分かりやすかったので
引用させていただきます。

idの値が分かっていて、そのidのデータを取得したい場合・・・find
idの値が不明で、id以外のカラムを検索条件としたい場合・・・find_by
id以外のカラムの検索条件で、複数の実行結果を取得したい場合・・・where

5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?