[RUBY] Create path from array

Create path from array

Besides using the routing helper, you can also create paths and URLs from an array of parameters. Consider the following routing

ruby.rb


resources :magazines do
  resources :ads
end

There are resources: ads (advertisements) in resources: magazines. If you use magazine_ad_path, instead of passing the id numerically You can pass an instance of Magazine and Ad as arguments respectively. Now you can refine the path with instance information for @magazine and @ad respectively.

<%= link_to 'Ad details', magazine_ad_path(@magazine, @ad) %>

You can also use url_for for a set of multiple objects. Even if you pass multiple objects, the proper routing is automatically determined.

<!--@with magazine@pass ad as an argument-->
<%= link_to 'Ad details', url_for([@magazine, @ad]) %>

In the above case, Rails will recognize that @magazine is Magazine and @ad is Ad and will call the magazine_ad_path helper based on that. It's amazing that you recognize this yourself. ..

Similarly, helpers such as link_to can simply pass an object instead of the full url_for call.

<%= link_to 'Ad details', [@magazine, @ad] %>

If you want to link to only one magazine, write:

<%= link_to 'Magazine details', @magazine %>

For all other actions, all you have to do is insert the action name in the first element of the array.

<%= link_to 'Edit Ad', [:edit, @magazine, @ad] %>

This allows you to treat an instance of the model as a URL. This is one of the great benefits of adopting a resourceful style.

It's amazing that Rails automatically generates a path by passing an instance to the path.

Reference Rails guide

Recommended Posts

Create path from array
Loading classes from Path
Array
[Java] Conversion from array to List
Array
Create a MySQL environment with Docker from 0-> 1
[Ruby] Get unique elements from an array
Cannot create user from Active Admin admin screen