如何控制或自定义 Rails 的 link_to() 用于模型的命名路由?

问题描述 投票:0回答:1

我有一个命名空间模型和控制器:

# 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

我想要:

  • URL 看起来像
    /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
模型。但事实并非如此。

我错过了什么吗?

ruby-on-rails routes
1个回答
0
投票

link_to
的简写版本只会根据您传入的对象的
.class
查找常规路径助手名称。它无法知道
@bar
对象或
FooStuff::Bar
类应该链接到该特定路线。想一想,这不像你以任何方式将 model 类与该路线关联起来。

© www.soinside.com 2019 - 2024. All rights reserved.