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 に答える