Как я могу отфильтровать эти сообщения и добавить их обратно в список? - PullRequest
0 голосов
/ 03 марта 2011

Как я могу заставить этот запрос работать, когда он проходит проверки перед добавлением его в массив записей? Я получаю следующую ошибку "не могу преобразовать сообщение в массив". Я предполагаю, что может быть лучший способ сделать запрос, но я не уверен, как это сделать.

Это в пользовательской модели, и я называю это в моем home_controller как current_user.personal_feed, а затем пытаюсь отобразить каждый результат.

Кроме того, у меня нет проблем с запросом сообщений у "друзей" пользователей, просто возникают проблемы только с добавлением сообщений, которые передают определенные параметры. Например, у них должен быть / slashtag, и пользователь также должен подписаться на этот 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 ]

2 голосов
/ 03 марта 2011
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 голосов
/ 04 марта 2011
  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

Окончательный фрагмент кода, который сработал.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...