LoginSignup
0
0

More than 5 years have passed since last update.

railsでlink_toを使いidを付与してリンクを作成

Last updated at Posted at 2017-04-13

railsでaタグにidなどを付けてリンクを作成したい場合があると思います。
詳細画面へ遷移させたい時に「/rentals/1」というパスを作成したい時です。

まず、どのようなパスが設定されているか調べる必要があります。

プロジェクトルートディレクトリで以下のコマンドを入力します。

rake routes

すると以下のような結果が出力されます。

 Prefix Verb URI Pattern            Controller#Action
   root GET  /                      homes#index
rentals GET  /rentals(.:format)     rentals#index
 rental GET  /rentals/:id(.:format) rentals#show

一番左のPrefix列に「_path」を付加したものがパスになります。

<%= link_to '詳細画面へ', rental_path(3) %>

上記のように記述すると「詳細画面へ」というテキストがリンクになり/rentals/3をパスに持つurlが作成されます。

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