如何过滤这些帖子然后将它们添加回列表?

时间:2011-03-03 20:43:53

标签: ruby-on-rails

如何在将查询添加到posts数组之前将此查询用于执行检查的位置?我收到以下错误“无法将Post转换为数组”。我假设可能有更好的方法来查询这个,但我不确定如何这样做。

这是在用户模型中,我在home_controller中将其称为current_user.personal_feed,然后尝试显示每个结果。

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

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

它不会引发任何错误,但它不会通过我的条件运行帖子。用户朋友的每个帖子仍在显示,即使他们没有订阅该个人订阅。

2 个答案:

答案 0 :(得分: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中将它们添加到数组中。

答案 1 :(得分: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

有效的最终代码段。

相关问题