0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

メモ Rails ConsoleでURLヘルパーを確認する方法

Posted at

Rails ConsoleでURLヘルパーを確認する方法

概要

Railsアプリケーションで定義されているURLヘルパーがどのようなURLを生成するかRails Consoleで確認したかったのでメモとして残します!

ルーティングの実装とヘルパーメソッド

基本的なリソースルート

# config/routes.rb
Rails.application.routes.draw do
  resources :users
end

この実装により、以下のヘルパーメソッドが自動生成されます:

  • users_path/users (一覧ページ)
  • user_path(id)/users/:id (詳細ページ)
  • new_user_path/users/new (新規作成ページ)
  • edit_user_path(id)/users/:id/edit (編集ページ)

ネストしたリソースルート

# config/routes.rb
Rails.application.routes.draw do
  resources :users do
    resources :posts
  end
end

この実装により、以下のヘルパーメソッドが生成されます:

  • user_posts_path(user_id)/users/:user_id/posts
  • user_post_path(user_id, post_id)/users/:user_id/posts/:id

Rails Consoleでの確認方法

1. Rails Consoleを起動

bundle exec rails console

2. URLヘルパーを読み込む

# URLヘルパーを読み込む
include Rails.application.routes.url_helpers

3. デフォルトのホストを設定

# URLを生成するためにホスト設定が必要
default_url_options[:host] = 'localhost:3000'

4. ヘルパーメソッドをテスト

# 例:ユーザー詳細ページのURLを生成
user_path(123)
# => "/users/123"

# 例:ユーザー詳細ページの完全なURLを生成
user_url(123)
# => "http://localhost:3000/users/123"

まとめ

簡単に確認できますね!

開発中にルートの動作を確認したい時や、デバッグ時に便利な方法です。
特に複雑なネストしたルートを確認する際に重宝するかなと!

おしまい

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?