LoginSignup
1
0

Couldn't find * with 'id'=* [rails エラー error]

Last updated at Posted at 2022-01-22

エラー内容

image.png

開発してるとこんなエラーがでる

「idがindexなんてTweetは見つけられなかったよ」って意味ですね!

エラーの解説

それはそう、だってDBの中に入っているレコードのidには、「1,2,3...」のような数字で割り振られてるから、その中から検索メソッド(今回はfindメソッド)を使って「index」という文字列でidを調べてもダメだよねって事です。

エラーの原因

問題はroutesにあります。

config/routes.rb
Rails.application.routes.draw do
  # 省略

  get 'tweets/:id' => 'tweets#show',as: 'tweet'
  get 'tweets/new' => 'tweets#new'
  post 'tweets' => 'tweets#create'
  patch 'tweets/:id' => 'tweets#update'
  delete 'tweets/:id' => 'tweets#destroy'
  get 'tweets/:id/edit' => 'tweets#edit', as:'edit_tweet'
  get 'tweets/index' => 'tweets#index'
  root 'hello#index'
end

大事なのは順番とパラメーターです。
routesは上から順番にHTTPメソッド(GETとかPOSTとか)とURLが一致しているものを探索していきます。
見つかった時点で、定義されたコントローラのアクションに遷移させます。

また、:idと書かれているものがパラメーターです。ここに情報が入ります。
例えば、Tweetのshowであれば、どのTweetの詳細を表示すれば良いのかidの情報をパラメーターに渡してあげることで、それぞれのTweetごとの情報が表示されます。
実際のURLがlocalhost:3000/tweets/2となれば、idが2のTweetが表示されるわけです!

ここで、わかりやすいように必要なところだけ抜き出しました。

config/routes.rb
Rails.application.routes.draw do
  # 省略
  get 'tweets/:id' => 'tweets#show',as: 'tweet'
  # 省略
  get 'tweets/index' => 'tweets#index'
end

そして、よく見てほしいのは
get 'tweets/:id' => 'tweets#show',as: 'tweet'
get 'tweets/index' => 'tweets#index'の順番です!

get 'tweets/:id'の方が上に来ていますね!
これが原因です。

URLがtweets/indexで来た時を考えましょう!そうするとtweets/:id:idの部分にindexが入っているように見えますよね。routesもそのように勘違いします。そして、そのままindexで検索してエラーという事です。

解決策

解決方法は2つです。

①順番を逆にしてあげましょう。

config/routes.rb
Rails.application.routes.draw do
  # 省略
  get 'tweets/index' => 'tweets#index'
  get 'tweets/:id' => 'tweets#show',as: 'tweet'
  # 省略
end

そうすれば、URLがtweets/indexで来た時は先にget 'tweets/index' => 'tweets#index'がマッチするので、正しく表示できます。

②resourcesを活用しましょう
煩雑なroutesも一発で定義してくれます。

config/routes.rb
Rails.application.routes.draw do
  # 省略
  resources :tweets
end

この場合はtweet#indexにアクセスするURLがlocalhost:3000/tweetsに変更になってるので、注意です!
routesがわからなくなったら、rails routesを使いましょう!

以上、エラーの解説でした!

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