Rails 3 - 具有范围资源的URL助手

时间:2011-09-22 18:23:04

标签: ruby-on-rails-3 routing urlhelper

我的路线文件中有一个范围内的资源:

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

使用'>耙路线'我得到标准路线,包括:

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

然而,当我使用控制台(这是我的测试失败)获取Mymodel实例的url时,我得到错误:

> 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>'

这可能是一个问题,但Mymodel也是使用标准Rails单表继承的子类。

有什么想法?为什么要查找physical_mymodel_url而不是mymodel_url?任何解决方法的想法,以便我仍然可以使用未加前缀的路由?

1 个答案:

答案 0 :(得分:2)

您只是使用示波器告诉它可以找到控制器的模块。如果您想在路线上使用physical前缀,那么您可以这样做:

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

或者,您可以使用namespace方法执行相同的操作:

namespace :physical do
  resources :mymodel
end