Coudn't findTweet with'id = index [rails 오류 error]

5123 단어 RubyRails

잘못된 내용



개발할 때 이런 오류가 발생할 수 있습니다.
"아이디가 index 같은 Tweet을 못 찾았어요"!

잘못된 해설


그건 DB에 기록된 id에'1, 2, 3...'이런 숫자로 분배되기 때문에 검색 방법(이번에find 방법)을 사용하고'인덱스'같은 문자열로 id를 찾는 것도 안 된다.

오류 원인


문제는 루스에 있습니다.
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라면 id 정보를 매개 변수에 전달함으로써 어느 Tweet의 상세한 정보를 표시하고 각 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' 위에 왔다!
그게 이유야.
URLtweets/index이 올 때를 생각해 봅시다!이렇게 하면 tweets/:id:id 부분에 index가 있는 것 같아요.루스도 그렇게 오해할 거야.그리고 직접 index 검색하는 것은 잘못된 것입니다.

해결책


해결 방법은 두 가지가 있다.
① 순서를 뒤집는다.
config/routes.rb
Rails.application.routes.draw do
  # 省略
  get 'tweets/index' => 'tweets#index'
  get 'tweets/:id' => 'tweets#show',as: 'tweet'
  # 省略
end
이렇게 하면 URLtweets/index이 왔을 때 선get 'tweets/index' => 'tweets#index'이 일치했기 때문에 정확하게 표시할 수 있다.
② 리소스를 활용하라
번잡한routes도 한꺼번에 정의할 수 있다.
config/routes.rb
Rails.application.routes.draw do
  # 省略
  resources :tweets
end
이 경우 방문tweet#index의 URL이 localhost:3000/tweets로 변경되었으니 주의하세요!
루틴을 모르면 rails routes를 사용하세요!
이상은 잘못된 해설입니다!

좋은 웹페이지 즐겨찾기