2012-06-03 50 views
0

比方說,我有一個User模型,其中has_many :posts,而Posthas_many :commentsActiveRecord是否可以設置爲自動限制二度關聯?

如果我這樣做@user.posts.map {|post| post.comments}.flatten我會得到全部對用戶帖子的評論。有沒有地方可以配置PostComment模型來檢測它在特定用戶的上下文中被引用,並且只返回特定用戶的評論?

也就是說,@user.posts.map {|post| post.comments}.flatten@posts.map {|post| post.comments}.flatten(假設相同的帖子)不會返回相同數量的評論(假設多個用戶評論)。

previous SO question's answers,這聽起來像我想某種nested has_many through。那是對的嗎? Rails 3中有沒有簡單的方法來檢測'源'?

+0

不知道我跟隨。這聽起來像你想找到一個特定用戶的評論,對吧?如果是這樣,你應該直接鏈接用戶和他/她的評論:即'用戶''has_many:評論'。不需要複雜的關係嵌套。 – Flambino

+0

正確,但我希望他們在帖子的上下文中。 – pr1001

+0

所以你想用戶的評論他/她自己的帖子? – Flambino

回答

1

更新答案:

下面是會得到文章作者的評論的方法

class Post < ActiveRecord::Base 
    belongs_to :user # So, there's a user_id attribute 
    has_many :comments 

    def authors_comments 
    comments.where("user_id = ?", user_id) 
    end 
end 

這應該讓你做:

@user.posts.each { |post| puts post, post.authors_comments } 

它並不像其他的方法一樣有效雖然; ñ的帖子將導致ñ SQL查詢以獲得評論。但它與下面評論中描述的內容非常接近。


原來的答覆(爲後人)

它是不是最漂亮的,但你可以這樣做

class User < ActiveRecord::Base 
    has_many :posts # All the user's posts 
    has_many :comments # All the user's comments on all posts 

    # All comments made on any of user's posts 
    has_many :replies, :through => :posts, :source => :comments 

    def replies_to_self 
    replies.where("comments.user_id = ?", id) 
    end 
end 

呼叫@user.replies_to_self的東西來獲取用戶的意見,以他/她自己的帖子

你最終得到這樣的SQL:

SELECT 
    "comments".* 
FROM 
    "comments" 
INNER JOIN 
    "posts" 
ON 
    "comments"."post_id" = "posts"."id" 
WHERE 
    "posts"."user_id" = X AND "comments"."user_id" = X 

(其中X將是用戶的ID)

+0

謝謝,但這並沒有解決我在找什麼:從用戶能夠引用帖子,然後在帖子內部能夠獲得用戶的評論。認爲像'@user.posts.each {| post | puts post,post.my_comments}' – pr1001

+0

@ pr1001更新了我的答案。仍然不知道這是你在找什麼,但在兩個答案之間,你應該能夠找到一種方法來做你想做的事,我希望 – Flambino

+0

謝謝Flambino,就是這樣! – pr1001

相關問題