2015-08-20 93 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

相关问题