2

我正在构建一个返回帖子列表的 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
      ]
    },
    …
  ]
}

这些帖子使用acts-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在我的模型中设置范围,因为acts-as-taggable-on 文档仅解释了如何根据标签名称查找对象(使用tagged_with()方法)。

预先感谢您的帮助!;-)

大卫

4

1 回答 1

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
于 2013-04-16T14:23:41.460 回答