Rails: Proper Routing for Name Extension Resources

If you add a resource map to the namespace in routes.rb in Rails 2.3, how do you do link_to (and form_for , etc.), understand that it should get a controller with a name extension instead of one in the root Namespace?

For example...

With this in routes.rb :

 map.namespace :admin do |admin| admin.resources :opt_in_users end 

And this is in the view:

 <%= link_to @anOptInUser %> 

That link_to should use link_for_admin_opt_in_user , but instead tries to use link_for_opt_in_user , which fails.

+6
ruby-on-rails
source share
4 answers

With resources with names, as well as with nested resources, you can use an array with a symbol:

 link_to 'Click here', [:admin, @opt_in_user] 

or

 form_for [:admin, @opt_in_user] do |form| .... 
+7
source share

docs rails for url_for indicate that you will need to explicitly call this:

If instead of a hash you pass a record (for example, an active record or an active Resource) as a parameter parameter, you will call the named route for this record. The search will occur in the class name. So, the workshop object will try to use route_path. If you have a nested route, for example admin_workshop_path you will have to call it explicitly (this is not possible for url_for to guess this route).

(from http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001564 )

+2
source share

Rails can accept an array of objects that are then mapped to a named route

eg. <% = link_to @ comment.title, [@article, @comment]%>

You will receive a link to /articles/@article.to_param/comments/@article.to_param

This can be used in form_for and other places as well

0
source share

Using:

 link_to '...', admin_opt_in_user_path(@anOptInUser) 

For a collection:

 admin_opt_in_users_path 

You can also add right and new prefixes.

When you use form_for, be sure to pass admin_opt_in_users_path for the new action and admin_opt_in_user_path (@anOptInUser) in the edit action.

0
source share

All Articles