【问题标题】:Rails link_to with acts_as_taggable_on_steroidsRails link_to 与acts_as_taggable_on_steroids
【发布时间】:2011-02-17 21:40:43
【问题描述】:

我正在使用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 标记/rails 指向路由标​​记/:id,并且我为 link_to 提供了一个附加参数以将标记名称分配为 :id 参数,但正如您所见,它不起作用.一个论坛建议我使用 to_param 但我没有 Tag 模型,这本书建议反对它。我错过了什么吗?

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      在黑暗中拍摄,但应该

      &lt;%= link_to tag, tag_path(:id =&gt; tag.name) %&gt;

      成为

      &lt;%= link_to tag, tag_path(:id =&gt; tag.id) %&gt;

      &lt;%= link_to tag, tag_path(tag) %&gt;

      【讨论】:

        【解决方案3】:

        试试这个链接:

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

        我不知道您使用的是什么版本的导轨,我假设是 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" =&gt; "tags#show"

        【讨论】:

          【解决方案4】:

          对我来说,这似乎是 routes.rb 之间的区别

          resources :tags
          

          resource :tags
          

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

          【讨论】:

            猜你喜欢
            • 2013-07-22
            • 2012-07-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多