2015-08-20 91 views
0

我正在嘗試獲取可追蹤項目和試圖獲取這些用戶的帖子。下面是我使用NoMethodError:未定義的方法`評論'爲#<Post :: ActiveRecord_Relation:0x007fbaee1f8f00>

def dashboard 
    @posts = [] 
    @Bposts = [] 
    @users = Follow.where('followable_type == ?',"User").where('follower_id == ?',current_user.id) 
    @blogs = Follow.where('followable_type == ?',"Blog").where('follower_id == ?',current_user.id) 
    @users.each do |user| 
     @posts << Post.where('user_id == ?',user.followable_id).where('blog_id == ?',nil) 
    end 
    @blogs.each do |blog| 
     @Bposts << Post.where('blog_id == ?',nil) 
    end 
    if @posts.count != 0 
     @posts.each do |post| 
     @comment = post.comments.build 
     end 
    end 
    if @Bposts.count != 0 
     @Bposts.each do |post| 
     @comment = post.comments.build 
     end 
    end 
    end 

回答

0
NoMethodError: undefined method `comments' for #<Post::ActiveRecord_Relation:0x007fbaee1f8f00> 

,因爲你是在<Post::ActiveRecord_Relation>對象調用comments您收到此錯誤代碼,但實際上你想做這個帖子對象。

目前,您@posts<Post::ActiveRecord_Relation>所以,當你遍歷@posts數組,每個post的是<Post::ActiveRecord_Relation>當你在調用它post.comments.build這是造成此錯誤。

要修正此錯誤,你必須改變這一點:

@users.each do |user| 
    @posts << Post.where('user_id == ?',user.followable_id).where('blog_id == ?',nil) 
end 

到:

@users.each do |user| 
    @posts << Post.where('user_id == ?',user.followable_id).where('blog_id == ?',nil).first 
end 

這樣一來,你會得到post對象的數組在@posts實例變量,然後你可以通過它們循環,每次獲得一個post並且對於每個post調用:post.comments.build

您還需要對@Bposts循環做類似的更改。確保你在Post對象上調用comment方法,而不是ActiveRecord_Relation對象。

+0

.first將只返回用戶的第一個帖子,但我試圖撤回用戶 – Mr94

+0

是的所有帖子,但是你做到這一點的方式,可能是這樣。如果你想這樣做,你需要在'@posts.each do | post |'循環裏面另外一個循環,因爲這樣每個帖子都會成爲一個'ActiveRecord_Relation'對象,這個對象也需要循環。 –

+0

有沒有簡單的方法來實現這個功能? – Mr94

相關問題