0
0

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 3 years have passed since last update.

違うメソッドが呼ばれた時の対処法

0
Posted at

前提条件

Rails 6.1.3

出てきたエラー

NoMethodError in PostsController#show

posts_controller.rb
def show
    @post = Post.find_by(id: params[:id])
    @user = @post.user エラー

不明点

showメソッドを呼んでないのに・・・NoMethodError in PostsController#showのエラーが出てしまう

結論・解決法

routes.rbの順番を入れ替える
変更前

routes.rb
Rails.application.routes.draw do
  get 'posts/:id' => 'posts#show'
  get 'posts/index' => 'posts#index'
end

変更後

routes.rb
Rails.application.routes.draw do
  get 'posts/index' => 'posts#index'
  get 'posts/:id' => 'posts#show'
end

補足

1.ルーティングとは

ルーティングとは送信されたURLに対してどのコントローラーのどのアクションで
処理するかを決める対応表のことです。
例えば get"posts#index"ではpostsコントローラーのindexアクションを呼び出すということです

2.ルーティングを実行する順番をする方法

$ rails routesを実行する
rails routesは各アクションのルーティングを確認する時、ルーティングを実行する順番を知りたい時に使います。

3.順番を逆にするとNoMethodErrorが出る理由

上から順にコードを優先していくため:idが先になるようにコードを書くと:id以外の特定のURLを読み取る前に:idを実行してしまうからです。

参考記事

Rails routes.rbに書く順番
Rails ルーティング 基礎 まとめ
ルーティングの順番について (Progateにて)  
rails routes(ルーティング)の順番の解説                 

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?