3
2

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.

link_toでURIに二つの引数を渡す

Posted at

はじめに

 以前に、link_toメソッドのpathの引数について投稿したが、本日、引数を2つ渡す状況があったので、忘れないために、まとめておく。

link_toメソッドとは

<% link_to '表示させる文字', ○○_path %>

とすることで、HTMLのaタグのような扱いができる。

pathに引数が必要な場合

ターミナルでrails routesのURIが、

/class_rooms/:class_room_id/messages/:id(.:format)

「:」と「id」がついてると、そこには引数を渡す必要がある。
:class_room_id:idに引数が必要。

pathに2つの引数を渡す必要がある場合

先の例で、
一つめの:class_room_idが必要になっているのは、ルーティングをネストしているため。

routes.rb
resources :class_rooms, only: [:index, :new, :create] do
    resources :messages, only: [:index, :create, :destroy]
  end

ルーティングをネストした場合は、link_toのpathの引数を二つ指定しなければならない。

<%= link_to '表示させる文字', class_room_message_path(@class_room, message) %>

指定する順番は、URIにある順番にする。

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?