views:

700

answers:

4

In Rails 2.3, if you add a resource map to a namespace in your routes.rb, how do you make link_to (and form_for and all those) understand that it should get that namespaced controller instead of one in the root namespace?

example:

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

link_to @anOptInUser #should use link_for_admin_opt_in_user,
# but tries to use link_for_opt_in_user, which fails
+1  A: 

Hi Joachim, the rails docs for url_for indicate you'd have to call this explicitly:

If you instead of a hash pass a record (like an Active Record or Active Resource) as the options parameter, you‘ll trigger the named route for that record. The lookup will happen on the name of the class. So passing a Workshop object will attempt to use the workshop_path route. If you have a nested route, such as admin_workshop_path you‘ll have to call that explicitly (it‘s impossible for url_for to guess that route).

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

Adam Alexander
Yeah, that's what I ended up doing… Thanks for confirming it's the only way! (although I wouldn't agree it's *impossible* for url_for to guess the route if there exists only one!)
Joachim Bengtsson
A: 

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

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

You'll get a link to /articles/@article.to_param/comments/@article.to_param

This can be used in form_for and other places as well

AdminMyServer
A: 

Use:

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

For collection:

admin_opt_in_users_path

You can also add edit and new prefixes.

When you use form_for be sure you pass admin_opt_in_users_path on new action and admin_opt_in_user_path(@anOptInUser) on edit action.

klew
+1  A: 

With namespaced resources, 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| ....
Tor Erik Linnerud