Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Correct routing for namespaced resources

If you add a resource map to a namespace in your routes.rb in Rails 2.3, how do you make link_to (and form_for, etc) understand that it should get the namespaced controller 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 in the view:

<%= link_to @anOptInUser %>

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

like image 836
nevyn Avatar asked Apr 08 '09 19:04

nevyn


2 Answers

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| ....
like image 99
Tor Erik Linnerud Avatar answered Sep 29 '22 00:09

Tor Erik Linnerud


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)

like image 22
Adam Alexander Avatar answered Sep 29 '22 00:09

Adam Alexander