2
可以说我有一个用户/ Post模型喜欢这里的例子:Rails的acts_as_taggable - tagged_with通过关系
https://github.com/mbleigh/acts-as-taggable-on#tag-cloud-calculations
用户有很多文章和帖子属于用户。帖子有标签。我可以轻松搜索具有特定标记帖子的用户吗?
可以说我有一个用户/ Post模型喜欢这里的例子:Rails的acts_as_taggable - tagged_with通过关系
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"]]
这样做的伎俩。我有问题,因为在我的第一次迭代中,我的用户模型中有acts_as_taggable启动,导致结果为零。 –