2

我正在使用acts_as_taggable_on 类固醇,我对生成标签链接的这段代码有问题:

<%= link_to tag, tag_path(:id => tag.name) %>

当我访问 URL 时:

http://localhost:3000/tags/rails

我得到错误:

No action responded to rails. Actions: show

但是,此 URL 有效:

http://localhost:3000/tags/show/rails

我在我的 tags_controller.rb 中定义了 show 动作

class TagsController < ApplicationController
  def show
    @stories = Story.find_tagged_with(params[:id])
  end
end

我有以下由 rake:routes 生成的路线:

           tags GET    /tags(.:format)                             {:controller=>"tags", :action=>"index"}
                POST   /tags(.:format)                             {:controller=>"tags", :action=>"create"}
        new_tag GET    /tags/new(.:format)                         {:controller=>"tags", :action=>"new"}
       edit_tag GET    /tags/:id/edit(.:format)                    {:controller=>"tags", :action=>"edit"}
            tag GET    /tags/:id(.:format)                         {:controller=>"tags", :action=>"show"}
                PUT    /tags/:id(.:format)                         {:controller=>"tags", :action=>"update"}
                DELETE /tags/:id(.:format)                         {:controller=>"tags", :action=>"destroy"}

所以我知道 URL tags/rails 指向路由 tags/:id,并且我为 link_to 提供了一个附加参数,以将标签名称分配为 :id 参数,但正如您所见,它不起作用。一个论坛建议我使用 to_param 但我没有 Tag 模型,这本书建议反对它。我错过了什么吗?

我正在关注 Sitepoint 的书《Simply Rails 2》

编辑:添加工作 URL,见顶部

4

4 回答 4

0

试试这个作为你的链接:

link_to tag.name, { :action => :tag, :id => tag.name }

我不知道你使用的是什么版本的rails,我假设是3。

基本上,您使用的是脱离 id 的 tag_path。如果您没有更改任何内容,则表示类似tag/43, 带有 id 43 的标签。建议您覆盖的原因to_param是,如果您希望它脱离标签的名称,例如tag/rails. 为此,您可以执行以下操作:

class Tag
  def to_param
    name
  end
end

最后,您必须更改显示操作以使用名称,而不是 id。所以@stories = Story.find_tagged_with(params[:name])。然后我相信你会想要创建一个路由来弥补这一点,所以在你的上方resources :tags,添加match "/tags/:name" => "tags#show".

于 2011-02-20T06:20:52.813 回答
0

尝试将此添加到您的路线资源:

:requirements => { :id => /.*/ }
于 2011-02-17T21:47:11.837 回答
0

在这里黑暗中拍摄,但应该

<%= link_to tag, tag_path(:id => tag.name) %>

<%= link_to tag, tag_path(:id => tag.id) %>

或者

<%= link_to tag, tag_path(tag) %>

于 2011-02-20T06:03:14.973 回答
0

对我来说,这看起来像是 routes.rb 之间的区别

resources :tags

resource :tags

第一个将作为其默认索引操作,第二个将没有 :index,但它会在默认路由上显示显示。

于 2011-02-24T20:53:07.010 回答