LoginSignup
1
0

More than 1 year has passed since last update.

[Rails] Prefixの使い方

Last updated at Posted at 2022-10-08

1.まずPrefixとは

URLに代わりの名前を付けて変数化したものです。

2.使い方

ターミナルで rails routes とコマンドを入力すると、以下のように表示されます。

       Prefix Verb   URI Pattern
                   Controller#Action
         tops GET    /tops(.:format)                                                                                tops#index
              POST   /schedules(.:format)                                                                           schedules#create
 new_schedule GET    /schedules/new(.:format)                                                                 s      chedules#new
edit_schedule GET    /schedules/:id/edit(.:format)                                                                  schedules#edit
     schedule GET    /schedules/:id(.:format)                                                                       schedules#show
              PATCH  /schedules/:id(.:format)                                                                       schedules#update
              PUT    /schedules/:id(.:format)                                                                       schedules#update
              DELETE /schedules/:id(.:format)                                                                       schedules#destroy

まず以下の1行について解説します。

new_schedule GET    /schedules/new(.:format)

左のnew_schedulesというのがPrefixとなり、new_schedule_pathというように最後に_pathを付けるとURI Patternのパスとして使うことができます。右の/schedule/newというURLを指定したい場合には、new_schedule_pathと記述することでそのURLに飛ばすことができます。

#Prefixを使用しない場合
<%= link_to "作成", '/schedules/new' %>

#Prefixを使用した場合
<%= link_to "作成", new_schedule_path %>

という使い方ができます。Prefixを使用した場合は''は使用しません。

また、

 schedule GET    /schedules/:id(.:format)                                                                       schedules#show
          PATCH  /schedules/:id(.:format)                                                                       schedules#update
          PUT    /schedules/:id(.:format)                                                                       schedules#update
          DELETE /schedules/:id(.:format)                                                                       schedules#destroy

のように一番左に何も書かれていない場合は、上と同じpathという意味になります。/schedules/:idであれば、schedule_pathとしたいところですが、これでは同じpathが出てきてしまうため、methodを指定します。

<%= link_to "削除する", schedule_path, method: :delete %>

ただし、デフォルトではgetがmethodとして指定されているので、getの場合は書いても書かなくても大丈夫です。

3.まとめ

リンクで別のURLへ飛ばしたいときには、ターミナルでrails routesコマンドを入力し、pathを確認しましょう。

参考にしたサイト
https://qiita.com/TAKA__m/items/c932ac0c07f9847ed63b

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