2010-11-13 55 views
6

我在Rails 3中使用acts_as_taggable_on v.2.0.3为帖子添加标签。我添加一个标签云,如下所述:https://github.com/mbleigh/acts-as-taggable-on,但我遇到了一个错误: ActionController :: RoutingError在帖子中#index:没有路由匹配{:action =>“tag”,:id =>“politics”, :控制器=> “职位”}。我的代码如下:Rails 3 - 使用acts_as_taggable_on v.2.0.3时发生路由错误

PostHelper:

module PostsHelper 
    include TagsHelper 
end 

型号帖子:

class Post < ActiveRecord::Base 
    ... 
    acts_as_taggable_on :tags 
end 

PostController中

class PostController < ApplicationController 
    ... 
    def tag_cloud 
    @tags = Post.tag_counts_on(:tags) 
    end 
end 

查看:

<% tag_cloud(@tags, %w(css1 css2 css3 css4)) do |tag, css_class| %> 
    <%= link_to tag.name, { :action => :tag, :id => tag.name }, :class => css_class %> 
<% end %> 

的routes.rb:

Blog::Application.routes.draw do 
    root :to => "posts#index" 
    resources :posts do 
    member do 
     post :notify_friend 
    end 
    collection do 
     get :search 
    end 
    resources :comments 
    end 
    resources :users 
    resource :session 
    match '/login' => "sessions#new", :as => "login" 
    match '/logout' => "sessions#destroy", :as => "logout" 
end 

我到底做错了什么?感谢您的回答。

+0

您可以发布您的routes.rb文件吗? – rwilliams 2010-11-13 21:17:22

+0

我将routes.rb文件添加到上面的问题中。 – 2010-11-13 21:38:08

回答

7

嗯,我想我明白了。 首先,我在这样的方式编辑routes.rb中:

resources :posts do 
    ... 
    collection do 
    get :tag 
    end 
end 

其次,我在PostController中添加的方法 “标签”:

def tag 
    @posts = Post.tagged_with(params[:id]) 
    @tags = Post.tag_counts_on(:tags) 
    render :action => 'index' 
    end 

它的工作原理!

0

对于Rails4 @muki_rails方法无效。这是我做过什么:

routes.rb

get 'tags/:tag' => 'articles#index', as: 'tag' 

现在我可以在视图中做到这一点(我使用slim):

- @article.tags.each do |tag| 
    = link_to tag.name, tag_path(tag.name) 

然后在我的ArticlesController如果params[:tag]变量被设置,我搜索匹配给定任务的所有相应的文章。

def index 
    if params[:tag].present? 
     @articles = Article.published.tagged_with(params[:tag]) 
    else 
     @articles = Article.published 
    end 
    end