2015-09-19 34 views

回答

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

这样做的伎俩。我有问题,因为在我的第一次迭代中,我的用户模型中有acts_as_taggable启动,导致结果为零。 –