Search code examples
ruby-on-rails-3routesurlhelper

Rails 3 - URL Helpers With Scoped Resource


I have a scoped resource in my routes file:

scope :module => "physical" do
    resources :mymodels
end

Using '> rake routes' I get the standard routes, including:

mymodel GET    /mymodels/:id(.:format)    {:action=>"show", :controller=>"physical/mymodels"}

However when I use the console (and this is what's failing in my tests) to get the url for instances of Mymodel I get errors:

> m = Physical::Mymodel.new
> => {...model_attributes...}
> m.save
> => true
> app.url_for(m)
> NoMethodError: undefined method `physical_mymodel_url' for #<ActionDispatch::Integration::Session:0x00000105b15228>
from /usr/local/lib/ruby/gems/1.9.1/gems/actionpack-3.0.7/lib/action_dispatch/testing/assertions/routing.rb:175:in `method_missing'
from /usr/local/lib/ruby/gems/1.9.1/gems/actionpack-3.0.7/lib/action_dispatch/routing/polymorphic_routes.rb:114:in `polymorphic_url'
from /usr/local/lib/ruby/gems/1.9.1/gems/actionpack-3.0.7/lib/action_dispatch/routing/url_for.rb:133:in `url_for'
from (irb):13
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.7/lib/rails/commands/console.rb:44:in `start'
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.7/lib/rails/commands/console.rb:8:in `start'
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.7/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

This might be a gotcha, but Mymodel is also a subclass using the standard Rails single table inheritance.

Any thoughts? Why is it looking for physical_mymodel_url instead of mymodel_url? Any ideas for workarounds so that I can still use the unprefixed routes?


Solution

  • You're only using the scope to tell it the module where the controller can be found in. If you want to use the physical prefix on your routes then you could do this:

    scope :module => "physical", :as => "physical" do
      resources :mymodel
    end
    

    Alternatively, you could just use the namespace method which will do the same thing:

    namespace :physical do
      resources :mymodel
    end