2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Rails][Route] Creating Paths and URLs From Objects

Posted at

2.9 Creating Paths and URLs From Objects
In addition to using the routing helpers, Rails can also create paths and URLs from an array of parameters. For example, suppose you have this set of routes:
resources :magazines do
  resources :ads
end
When using magazine_ad_path, you can pass in instances of Magazine and Ad instead of the numeric IDs:
<%= link_to 'Ad details', magazine_ad_path(@magazine, @ad) %>

magazine_ad_pathに対して、IDを表す数値ではなく、オブジェクトを渡すことができる。

You can also use url_for with a set of objects, and Rails will automatically determine which route you want:
<%= link_to 'Ad details', url_for([@magazine, @ad]) %>

Magazine ModelとAd Modelと見なして、magazine_ad_pathを使用してくれる。

In this case, Rails will see that @magazine is a Magazine and @ad is an Ad and will therefore use the magazine_ad_path helper. In helpers like link_to, you can specify just the object in place of the full url_for call:

link_toメソッドなどのヘルパーでは、名前付きパスの部分にModelを渡してもいい。

<%= link_to 'Ad details', [@magazine, @ad] %>
If you wanted to link to just a magazine:
<%= link_to 'Magazine details', @magazine %>
For other actions, you just need to insert the action name as the first element of the array:
<%= link_to 'Edit Ad', [:edit, @magazine, @ad] %>

アクションを指定したいときは、配列の先頭要素として、アクション名を渡す。

This allows you to treat instances of your models as URLs, and is a key advantage to using the resourceful style.
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?