2013-04-15 40 views
2

我建立一個返回崗位(本地主機:3000/API/V1 /帖):列表的API如何在has_scope上使用acts-as-taggable-on?

{ 
    "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 
     ] 
    }, 
    … 
    ] 
} 

這些職位上使用的行爲,如,加標籤,寶石標記。我希望能夠基於使用has_scope寶石這些標籤來過濾他們(本地主機:3000/API/V1 /職位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作用域,因爲作爲標記的行爲文檔僅基於其標記名稱(使用tagged_with()方法)解釋how to find objects

非常感謝您的幫助! ;-)

大衛

回答

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 
+0

在這種情況下, ,過濾的帖子URL是:localhost:3000/api/v1/posts?tagged_with_id = 1 – davidg

相關問題