Rails link_to with acts_as_taggable_on_steroids

时间:2011-02-17 21:40:43

标签: ruby-on-rails ruby acts-as-taggable-on clean-urls

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

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

当我访问网址时:

http://localhost:3000/tags/rails

我收到错误:

No action responded to rails. Actions: show

但是,此网址有效:

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标签/ rails指向路由标​​签/:id,我已经为link_to提供了一个额外的参数,以将标签名称指定为:id param,但正如您所看到的,它不起作用。一个论坛建议我使用to_param,但我没有Tag模型,而且建议反对它。我错过了什么吗?

我正在关注Sitepoint一书Simply Rails 2

编辑:添加了工作网址,请参见顶部

4 个答案:

答案 0 :(得分:0)

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

:requirements => { :id => /.*/ }

答案 1 :(得分:0)

在黑暗中拍摄,但应该

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

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

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

答案 2 :(得分: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

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

答案 3 :(得分:0)

对我而言,看起来像

之间的routes.rb的区别
resources :tags

resource :tags

第一个将作为其默认索引操作,第二个将没有:index,但它将以默认路由上的show响应。