ruby-on-rails - Rails acts_as_taggable - 通过关系进行 tagged_with

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

假设我有一个用户/帖子模型,如下例所示:

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

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

最佳答案

所以你基本上有:

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"]]

关于ruby-on-rails - Rails acts_as_taggable - 通过关系进行 tagged_with,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32665883/

相关文章:

ruby-on-rails - Ruby 自定义方法链

ruby-on-rails - 可以将hadoop用作Rails应用程序上的ruby的数据库/后端吗?

ruby-on-rails - 如何在宿主应用程序中呈现 Rails 引擎的 View

ruby-on-rails - Rails where LIKE 和 array

javascript - rails 5 : Why is javascript executing twice?

ruby-on-rails - rails 找到帖子的 user_id = user 的所有评论

使用 Rails/ActiveRecord 的 MySQL 函数

ruby-on-rails - 如何设置标签的最小和最大数量?

ruby-on-rails - 使用acts_as_taggable_on获取特定所有者的标签计数列表

ruby-on-rails - Acts_as_taggable_on 索引太长