2011-03-03 20 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 

工作的最終代碼片段。

相關問題