Rails acts_as_taggable - tagged_with通过关系

时间:2015-09-19 08:11:21

标签: ruby-on-rails activerecord acts-as-taggable-on

假设我有一个类似于此处示例的用户/帖子模型:

https://github.com/mbleigh/acts-as-taggable-on#tag-cloud-calculations

用户有很多帖子和帖子属于用户。帖子有标签。我可以轻松搜索具有特定标记帖子的用户吗?

1 个答案:

答案 0 :(得分:2)

所以你基本上有:

class User
  has_many :posts
end

class Post
  acts_as_taggable

  # under the hood, this declaration creates
  # following relations
  has_many :tags
  has_many :taggings
end

您现在可以将以下关系添加到User

class User
  has_many :posts
  has_many :tags, through: :posts
  # has_many :taggings, through: :posts
end

现在查询给定的@tag应该很简单:

users_with_give_tag = User.joins(:tags).where("tags.id=?", @tag.id)

生成以下SQL:

SELECT "users".* FROM "users"
INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
INNER JOIN "taggings" ON "taggings"."taggable_id" = "posts"."id" AND "taggings"."context" = ? AND "taggings"."taggable_type" = ?
INNER JOIN "tags" ON "tags"."id" = "taggings"."tag_id"
WHERE (tags.id=1)  [["context", "tags"], ["taggable_type", "Post"]]