This content originally appeared on DEV Community and was authored by Akshay Khot
In Rails, routes map an incoming URL to a controller action. When you define a route for your application, you also get path and URL helpers to build relative or absolute URLs from the route's name. For example, suppose that you have a users
resource in your config/routes.rb
:
resources :posts
This route creates the method posts_path
that you can use in the view. For simple routes, you can probably guess the output of the helper, e.g., the posts_path
helper will return the URL /posts
. For complex routes, especially nested ones, it can be hard to figure out the URL until you use the helper to render the view.
This post shows a simple way to check the output of URL and path helpers directly from the Rails console. We will also see how to access these helpers in your models.
Here's a typical route file with a single route.
# routes.rb
Rails.application.routes.draw do
get '/posts/:id/preview', to: 'posts#preview', as: "preview_post"
end
This route maps the URL posts/:id/preview
to PostsController#preview
action. Additionally, we have named the route preview_post
using the as
option. Hence, Rails will automatically generate preview_post_path
and preview_post_url
helpers for us.
To see the routes in your application, you can run the rails routes
command.
> bin/rails routes -g preview
Prefix Verb URI Pattern Controller#Action
preview_post GET /posts/:id/preview(.:format) posts#preview
However, this doesn't tell you what URL the route will generate for you. For that, you can call the helper methods on the app
object, which represents your application. Rails adds all the helpers to the app
object when it boots. Hence you can check the output of any named route helper in the console, which is pretty handy during development.
irb(main):018:0> post = Post.first
irb(main):019:0> app.preview_post_path(post)
=> "/posts/5/preview"
Accessing Helpers from Models
By default, the helper methods are accessible from your controllers, views, and mailers. If you need to access the auto-generated helper methods from other places (such as a model), then you can do that by including Rails.application.routes.url_helpers
in your class:
class Post < ActiveRecord::Base
include Rails.application.routes.url_helpers
def link
post_path(self)
end
end
Post.find(1).link # => "/posts/1"
I hope that helps.
This content originally appeared on DEV Community and was authored by Akshay Khot
Akshay Khot | Sciencx (2022-04-20T02:05:14+00:00) Accessing Route Helpers from Rails Console. Retrieved from https://www.scien.cx/2022/04/20/accessing-route-helpers-from-rails-console/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.