如何在has_scope中使用act-as-taggable-on?

时间:2013-04-15 16:30:52

标签: ruby-on-rails acts-as-taggable-on has-scope

我正在构建一个返回帖子列表的API(localhost:3000 / api / v1 / posts):

{
  "tags": [
    {
      "id": 1,
      "name": "Tag 1"
    },
    {
      "id": 2,
      "name": "Tag 2"
    },
    …
  ],
  "posts": [
    {
      "id": 1,
      "title": "Post 1",
      "body": "Lorem ipsum dolor sit amet.",
      "tag_ids": [
        1
      ]
    },
    {
      "id": 2,
      "title": "Post 2",
      "body": "Lorem ipsum dolor sit amet.",
      "tag_ids": [
        2
      ]
    },
    …
  ]
}

这些帖子使用 act-as-taggable-on gem进行标记。我希望能够使用 has_scope gem(localhost:3000 / api / v1 / posts?tag_id = 1)根据这些标记过滤它们:

{
  "tags": [
    {
      "id": 1,
      "name": "Tag 1"
    }
  ],
  "posts": [
    {
      "id": 1,
      "title": "Post 1",
      "body": "Lorem ipsum dolor sit amet.",
      "tag_ids": [
        1
      ]
    }
  ]
}

但我不知道如何在我的模型中设置by_tag_id范围,因为act-as-taggable-on文档仅根据其标记名称解释how to find objects(使用tagged_with() }方法)。

提前感谢您的帮助! ; - )

大卫

1 个答案:

答案 0 :(得分:3)

对于那些感兴趣的人,我解决了这样的问题......这是我的Post模型:

class Post < ActiveRecord::Base
  attr_accessible :title, :body, :tag_list

  # Alias for acts_as_taggable_on :tags
  acts_as_taggable

  # Named scope which returns posts whose tags have a specific ID
  scope :tagged_with_id, lambda { |tag_id| joins(:taggings).where(:taggings => {:tag_id => tag_id}) }
end

我的帖子控制器:

class PostsController < ApplicationController
  has_scope :tagged_with_id

  def index
    @posts = apply_scopes(Post).all

    render :json => @posts
  end
end