2011-09-22 47 views
0

我在我的路線文件範圍的資源:的Rails 3 - URL傭工作用域資源

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?任何變通辦法的想法,以便我仍然可以使用前綴無前例的路線?

回答

2

你只使用範圍告訴它的控制器中可以找到該模塊如果你想使用physical前綴對你的路線,那麼你可以這樣做:

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

另外,你可以使用namespace方法,它會做同樣的事情:

namespace :physical do 
    resources :mymodel 
end 
+0

我想* ommit *前綴的路由幫助器方法。當我希望它使用mymodel_url時,它似乎期望基於錯誤消息的physical_mymodel_url。 mymodel_url應該基於rake路由輸出工作。 –

+1

事實證明,url_for方法調用ActiveRecord類的ActiveRecord :: Naming複數方法。這會返回「physical_mymodels」,這是URL邏輯其餘部分的基礎。根本沒有與路線文件的聯繫,因此無法知道模型不使用前綴。看起來我需要使用Ryan Bigg解決方案的前綴路徑,或修改Physical模塊中所有模型的ActiveRecord基礎以覆蓋url_for並剝離模塊前綴。 –