列出acts_as_taggable的所有标签

Zac*_*ack 1 ruby-on-rails acts-as-taggable-on

我有一个应用程序,其中包含使用acts_as_taggable gem的标签.我目前已经进行了设置,因此当在factoid的索引页面上时,单击任何标签会按该标记过滤factoids.我现在尝试做的是创建一个列出应用程序中所有标签的索引页面.这似乎很直接......

  1. 创建一个 tag.rb
  2. 创建一个 tags_controller.rb
  3. 添加视图 tags/index.html.erb

问题是这导致我之前实现的搜索中断.如果还有其他需要的东西,请告诉我.

FactoidsController(它的索引部分)

class FactoidsController < ApplicationController
  helper_method :sort_column, :sort_direction
  before_filter :authenticate_user!

  # GET /factoids
  # GET /factoids.json
  def index
    if params[:tag]
      @factoids = Factoid.tagged_with(params[:tag]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 15, :page => params[:page])
    else
      @factoids = Factoid.search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 15, :page => params[:page])
    end

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @factoids }
    end
  end

  def tagged
    if params[:tag].present?
      @factoids = Factoid.tagged_with(params[:tag])
    else
      @factoids = Factoid.postall
    end
  end

  private
  def sort_column
    params[:sort] || "created_at"
  end

  def sort_direction
    params[:direction] || "desc"
  end

end
Run Code Online (Sandbox Code Playgroud)

标签控制器

class TagsController < ApplicationController
  helper_method :sort_column, :sort_direction
  before_filter :authenticate_user!

  # GET /factoids
  # GET /factoids.json
  def index
    @tags = Tag.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @tags }
    end
  end

  private
  def sort_column
    params[:sort] || "created_at"
  end

  def sort_direction
    params[:direction] || "desc"
  end

end
Run Code Online (Sandbox Code Playgroud)

路线

QaApp::Application.routes.draw do
  devise_for :users

  resources :factoids

  resources :tags

  get "home/index"

  match 'tagged' => 'factoids#tagged', :as => 'tagged'

  get 'tags/:tag', to: 'factoids#index', as: :tag

  root :to => 'home#index'

end
Run Code Online (Sandbox Code Playgroud)

Zer*_*ber 6

您不需要经历创建标签模型和控制器的所有麻烦.`acts-as-taggable-on提供了一种查找模型所有标签列表的方法.

2.0.0-p451 :008 > Factoid.tag_counts
  ActsAsTaggableOn::Tag Load (2.0ms)  SELECT tags.*, taggings.tags_count AS count FROM "tags" JOIN (SELECT taggings.tag_id, COUNT(taggings.tag_id) AS tags_count FROM "taggings" INNER JOIN factoids ON factoids.id = taggings.taggable_id WHERE (taggings.taggable_type = 'Factoid' AND taggings.context = 'tags') AND (taggings.taggable_id IN(SELECT factoids.id FROM "factoids")) GROUP BY taggings.tag_id HAVING COUNT(taggings.tag_id) > 0) AS taggings ON taggings.tag_id = tags.id
 => #<ActiveRecord::Relation [#<ActsAsTaggableOn::Tag id: 1, name: "tag">]>
Run Code Online (Sandbox Code Playgroud)

这将返回所有标记对象的ActiveRecord :: Relation.您可以在其上运行地图以获取标记数组

Factoid.tag_counts.map(&:name)
 => ["tag"]
Run Code Online (Sandbox Code Playgroud)