2015-09-19 62 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啓動,導致結果爲零。 –