2
1

More than 3 years have passed since last update.

RailsコンソールでパスのURLを確認する

Last updated at Posted at 2021-05-24

はじめに

Railsで〇〇_pathと指定することがあるかと思います。
ではそのパスはどのURLに対応しているのかを確認する方法はどうすればいいのかをまとめます。

$\mathbb{それでははじめていきましょう}$

rails routesでルートを確認する

コンソール
% rails routes 

rails routesでパスを確認します。


例えばこんな結果が返ってきたとします。

結果
Prefix           Verb   URI Pattern                          Controller#Action                                                                 
root             GET    /                                    items#index
items            GET    /items(.:format)                     items#index
                 POST   /items(.:format)                     items#create
new_item         GET    /items/new(.:format)                 items#new
edit_item        GET    /items/:id/edit(.:format)            items#edit
item             GET    /items/:id(.:format)                 items#show
                 PATCH  /items/:id(.:format)                 items#update
                 PUT    /items/:id(.:format)                 items#update
                 DELETE /items/:id(.:format)                 items#destroy

色々とパスが書かれていますがまずはroot_pathのURLを見ていきましょう。

パスの確認方法

pathの確認には

パスの確認
pry(main)> app.Prefixに書かれたパス名.path

とします。
ルートパスのURLを確認します。

pry(main)> app.root_path

と入力すると

pry(main)> app.root_path
=> "/"

と表示されます。

items.pathのURLも確認してみましょう。

pry(main)> app.items_path
=> "/items"

表示されました。

パスはこのURLを表しているだけなので、フォームなどで

rails_form
<%= form_with url: '/items/new' do |f| %>

とすることもできますってことですね。

URLを表示させる

そしてURL(http://○○○.com)などと表示させるには

URL確認
pry(main)> app.Prefixに書かれたパス名.url

とします。
root_pathのURLを表示させてみます。

pry(main)> app.root_url
pry(main)> app.root_url
=> "http://www.example.com/"

表示できました。



参考サイト
- Qiita Rails | rails console で ルーティングのパスを確認する
- Qiita Rails console で Rails routes を詳しく確認する方法
- Qiita Rails でリンクパスを生成する方法色々・・とRails console で 生成される path を確認したい時

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