我有一个命名空间模型和控制器:
# app/controllers/foo_stuff/bars_controller.rb
module FooStuff
class BarsController < ApplicationController
# ..
end
end
# app/models/foo_stuff/bar.rb
module FooStuff
class Bar < ApplicationRecord
# ...
end
end
我想要:
/foo/1
,它将路由到 FooStuff::BarController#show
。foo_url
,例如foo_url(@bar)
。我的路线设置如下:
# config/routes.rb
scope module: 'foo_stuff', as: 'foo' do
resources :bars, path: 'foo'
end
当我运行
rails routes
时,这看起来是正确的。
但是,当我尝试时:
<%= link_to('Something', @bar) %>
...Rails 抱怨
undefined method 'foo_stuff_bar_url' for an instance of #<Class:...>
。
如果我明确使用命名路由就可以了:
<%= link_to('Something', foo_url(@bar) %>
我预计
link_to()
会从路线中找出什么命名的路线助手来调用 @bar
模型。但事实并非如此。
我错过了什么吗?
link_to
的简写版本只会根据您传入的对象的.class
查找常规路径助手名称。它无法知道@bar
对象或FooStuff::Bar
类应该链接到该特定路线。想一想,这不像你以任何方式将 model 类与该路线关联起来。