2013-05-27 119 views
0

我有一個關於我的網站的問題。方案如下:Ruby on Rails有很多關係

用戶和帖子有很多評論。 評論屬於用戶和帖子。

我做

@specificpost = Post.first 

然後

@specificpost.comments 

工作完全正常。 但問題是這樣的:

@currentuser = User.first 

工作完全正常。

@currentuser.posts 

給我的職位反對, 但是當我做

@currentuser.posts.comments 

評論是無法識別的。

Succintly,我想所有的都寫在@currentuser職務

感謝您遠閱讀本評論! :)

+0

你想對當前用戶的每個帖子的評論數? @ current_user.posts.map {| P | p.comments.count}將返回每個帖子的評論數。 – rmagnum2002

+0

Orif你需要評論@ current_user.posts.map {| p | p.comments}將獲得數組中每個帖子的評論。 – rmagnum2002

回答

1

@currentuser.posts給我的帖子對象

NO。它給出了一個集合Post對象。他們每個人都有自己的意見,但集合本身不(這是一個集合,畢竟,不是一個職位)。

我想所有的都寫在@currentuser

後的文章的評論?你有幾個。你想要哪一個?

# comments of first post (if user has no posts, error will be raised. Also applies to other methods) 
@current_user.posts.first.comments 

# comments of last post 
@current_user.posts.last.comments 

# all comments of all posts 
@current_user.posts.each_with_object([]) {|comments, memo| memo += comments} 
+0

當我說@ current_user.posts.each_with .. etc時,它給出了一個錯誤,說明未定義的方法'each_with_object'爲零:NilClass – Yagiz

+2

這意味着'@ current_user.posts'是'nil'。你確定你已經建立了正確的關係,並且這個用戶確實有帖子嗎? –