6

我在 Rails 3 中使用acts_as_taggable_on v.2.0.3 为帖子添加标签。我添加了一个标签云,如下所述:https://github.com/mbleigh/acts-as-taggable-on,但我遇到了一个错误: ActionController::RoutingError in Posts#index: No route matches {:action =>“标签”,:id=>“政治”,:控制器=>“帖子”}。我的代码如下:

邮政助手:

module PostsHelper
  include TagsHelper
end

模型帖子:

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

后控制器

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 %>

路线.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

我究竟做错了什么?感谢您的回答。

4

2 回答 2

7

嗯,我想我明白了。首先,我以这种方式编辑了 routes.rb :

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

其次,我在 PostController 中添加了方法“Tag”:

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

有用!

于 2010-11-14T08:23:34.737 回答
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)

然后在我的ArticlesControllerifparams[:tag]变量设置中,我搜索与给定任务匹配的所有相应文章。

  def index
    if params[:tag].present?
      @articles = Article.published.tagged_with(params[:tag])
    else
      @articles = Article.published
    end
  end
于 2016-05-26T09:39:54.030 回答