【问题标题】:How to use acts-as-taggable-on with has_scope?如何在 has_scope 中使用作为可标记的行为?
【发布时间】:2013-04-15 16:30:52
【问题描述】:

我正在构建一个返回帖子列表的 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 文档仅根据标签名称解释how to find objects(使用tagged_with()方法)。

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

大卫

【问题讨论】:

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


    【解决方案1】:

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

    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
    

    【讨论】:

    • 在这种情况下,过滤后的帖子 URL 为:localhost:3000/api/v1/posts?tagged_with_id=1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多