2011-03-03 41 views
0

如何在将查询添加到posts数组之前通过检查来使这个查询工作?我收到以下错误“无法将帖子转换为数组”。我假设可能有更好的方法来查询,但我不确定如何去做。如何过滤这些帖子,然后将它们添加回列表中?

这是在用户模型中,我在我的home_controller中调用了current_user.personal_feed,然后试图显示每个结果。

另外,我没有任何问题查询用户“朋友”的帖子只是有问题只添加通过某些参数的帖子。比如他们必须在他们/斜杠标签,并且用户还必须订阅该斜杠标签

def personal_feed 
     posts = [] 
     # cycle through all posts (of the users "friends) & check if the user wants to see them 
     Post.find(:all, :conditions => ["user_id in (?)", friends.map(&:id).push(self.id)], :order => "created_at desc").each do |post| 
     # first checkpoint: does this post contain a /slashtag 
     post.message.scan(%r{(?:^|\s+)/(\w+)}).map {|element| 
      # second checkpoint: does this user subscribe to any of these slashtags? 
      if self.subscriptions.find_by_friend_id_and_slashtag(post.user.id, element[0]) 
      posts += post 
      end 
     } 
     end 
    end 

我已经改变了代码这一点。

def personal_feed 
    posts = [] 
    # cycle through all posts (of the users "friends) & check if the user wants to see them 
    Post.find(:all, :conditions => ["user_id in (?)", friends.map(&:id).push(self.id)], :order => "created_at desc").each do |post| 
     # first checkpoint: does this post contain a /slashtag 
     post.message.scan(%r{(?:^|\s+)/(\w+)}).map {|element| 
     # second checkpoint: does this user subscribe to any of these slashtags? 
      posts << post if self.subscriptions.find_by_friend_id_and_slashtag(post.user.id, element[0]) 
     } 
    end 

它不会引发任何错误,但它不经过我的条件下运行的职位。即使用户朋友没有订阅该个人订阅,仍然会显示用户朋友的每篇帖子。

+0

帖子+ =帖子不起作用的原因是因为该语法想要将两个数组一起添加。但帖子是一个数组。因此,要将帖子添加到帖子中,您将会发布帖子<<帖子,或posts.push(帖子) – 2011-03-03 21:00:06

+0

谢谢。这不会引起任何错误,但我似乎无法让它通过我的不同条件。 – morcutt 2011-03-03 21:19:32

回答

2
def personal_feed 
    if user_signed_in? 
     @good_friends = [] 
     current_user.friends.each do |f| 
     @good_friends << f #if some condition here 
     end 
    else 
     #cannot find friends because there is not a current user. 
     #might want to add the devise authenticate user before filter on this method 
    end 
end 

查找当前用户,然后遍历他们的朋友,只有将它们添加到数组如果xyz。

+0

我正在使用设计。我会尝试使用这种方法。 – morcutt 2011-03-03 20:57:05

+0

在这种情况下,我更新了代码。 – s84 2011-03-03 20:58:54

+0

查看我编辑的原始文章中的代码。为什么我的条件不起作用?即使我将条件改变为我所知道的不真实的情况,它也会添加每一篇文章。 – morcutt 2011-03-03 21:34:40

0
def personal_feed 
     posts = [] 
     # cycle through all posts (of the users "friends) & check if the user wants to see them 
     Post.find(:all, :conditions => ["user_id in (?)", friends.map(&:id).push(self.id)], :order => "created_at desc").each do |post| 
      # first checkpoint: does this post contain a /slashtag 
      post.message.scan(%r{(?:^|\s+)/(\w+)}).map {|element| 
      # second checkpoint: does this user subscribe to any of these slashtags? 
      posts << post if self.subscriptions.find_by_friend_id_and_slashtag(post.user.id, element[0]) 
      } 
     end 
     posts = posts 
    end 

工作的最终代码片段。

相关问题