我正在构建一个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- tagable -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- tagable -on文档只解释了如何根据它们的标记名称(使用tagged_with()
方法)找到对象。
提前感谢您的帮助!: -)
大卫对于那些感兴趣的,我解决了这样的问题,这是我的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
和我的Posts控制器:
class PostsController < ApplicationController
has_scope :tagged_with_id
def index
@posts = apply_scopes(Post).all
render :json => @posts
end
end