Using named routes versus using url_for ()

When should you use named routes against using url_for with the hash {: controller => "somecontroller" ,: action => "someaction"}?

Is preferred over others and why? Is another supported or more efficient wrt performance?

+4
source share
4 answers

This may help to understand what named routes do.

Defining a named route creates a wrapper around url_ to provide the parameters needed for the created route. Routing resources create many named routes.

Given this, the overhead of calling a named route, unlike url_for with the necessary parameters, is negligible. Therefore, if you bind to a specific resource, then named routes are the way to go. They are easier to read, print and maintain.

However, do not drop url_for. It has many creative possibilities due to the way it handles missing parameters. This is very useful when it comes to storing DRY views that are used from multiple sub-sources. That is: when you have a blog_posts controller and a posts_controller controller using the same views.

I highly recommend you read url_for documentation . To help figure out where these places make sense to use url_for, follow these steps:

+3
source

I would prefer the named routes to be shorter and do the same.

0
source

the named route is very neat.

map.with_options :controller => "company", :action => "show", :panel => "name" do |m| m.company '/company/:action/:id/:panel' end 

Then you can call

 company_url :id => 1 
0
source

If you carefully configure your routes and resources, you do not need any hash routes, only named ones (either built-in via map.resource or custom map.<something> ). Hash routes are useful if you need to create links based on dynamic content. Sort of:

 link_to @post.title, :controller => (@user.is_admin ? 'admin/posts' : 'public/posts'), :action => 'show', :id => @post 

(This is just a forced example, but you should get its gist :)

0
source

Source: https://habr.com/ru/post/1301414/


All Articles