Ruby Pill #1
Rails routes tricks
2018-10-01 , 5 minutes read, 319 views 0 comments
In this short article I will present you three non-obvious things about rails routes that I've encountered recently. Maybe some of these will be helpful!
Ways of listing your app routes
I bet you knew that calling this peace of code:
# List all routes in the system rake routes # Alias for rails 5 or higher rails routes
renders nice output of all routes directly in your console. You could even use fancy command to only see what's important to you, like this:
# See all routes with word "user" in it rake routes | grep user # See all routes without word "user" in it rake routes | grep -v user
or if you know secret parameters of this rake task:
# See all routes from users controller rake routes -c users
but... did you know, that you can access routes directly in browser, without even touching the terminal? Just go to
while your app is running and enjoy beautiful page with js search in it!
You need Rails in version 4 or higher to see it - and that's because of gem Sextant added to it. That's not the only thing you can find under rails/info - google it! Of course, for safety reasons, this page is accessible only when app runs in development mode.
Working with routes in RubyMine
If you're using RubyMine like me, then you probably heard about different plugins on JetBrains marketplace. One of the plugins that can be helpful while working with rails routing is Railways - this tool may allow you not only to list routes in enjoyable way, but also to quickly jump straight to implementation of a route.
Personally I stopped using it after few months - if you enjoy mastering keyboard shortcuts of IDEA products, and busting out max of IDE productivity, you may quickly find out that famous JetBrains search enginge allows you to jump to implementation faster than navigating through new tab that plugin provides.
Still - it may be more enjoyable than using rake task or opening 25th tab in our beloved browser.
Accessing nested routes shortcut
Imagine that you have routes like this:
resources :brands do resources :products end
And now you have two places in your code when you need to make redirect. In one - redirect to brand, and in second to the product of that brand. How would you do that? Probably like that:
# Redirect to brand redirect_to @brand # Redirect to given brand product redirect_to brand_product_path(@brand, @product)
There's a shorter way!
# Redirect to brand redirect_to @brand # Redirect to given brand product redirect_to [@brand, @product]
It works not only for simple show pages, but also other routes:
# Redirect to given brand product edit page redirect_to [:edit, @brand, @product] # Redirect to given brand products index redirect_to [@brand, :products]
You can apply the same principle to places where you usually pass single model (like forms). I learned this tip from Drifting Ruby. Enjoy!