2014-11-26 5 views
0

연습을 위해 레일 4를 사용하여 Twitter 클론을 만들고 있습니다. 사용자가 로그인하면 타임 라인에 따라 내가 팔로우하는 사람들 (친구)의 트윗과 자신의 트윗을 DESC 순서로 표시하고자합니다. 내 트위트 # index를 내 타임 라인으로 사용하고 있습니다. 현재 내가 사용자에게 데이터베이스의 모든 트윗을 표시하고 있습니다 : 컨트롤러에서 배열을 반복하는 방법

def index 
    @tweets = Tweet.all.order("created_at DESC") 
end 

내가 사용자의 친구에 기록 전류를 포함 @user_friendships라는 인스턴스 변수를 추가, 마녀 그때를 통해 반복하고 자신의 트윗에 액세스 할 수 있습니다. 내가 user_friendships을 통해 루프를 원하고 CURRENT_USERS의 트윗을 통해 친구와 다음 트윗 뷰뿐만 아니라 루프의 잡아하지 않습니다

def index 
    @user_friendships = current_user.user_friendships.all 
    @tweets = Tweet.all.order("created_at DESC") 
end 

: 여기처럼 지금 모습입니다.

컨트롤러에서 user_friendships에있는 current_user 및 각 친구 트윗의 트윗을 포함하는 인스턴스 변수를 하나 갖고 싶습니다. View에서 새로운 배열을 반복하기 만하면됩니다.

모델 코드

### User.rb 

has_many :tweets 

has_many :user_friendships 
has_many :friends, through: :user_friendships 

acts_as_voter 

def to_param 
    username 
end 

### user_friendship.rb 

belongs_to :user 
belongs_to :friend, class_name: 'User', foreign_key: 'friend_id' 


### tweet.rb 

belongs_to :user 

답변

1
def index 
    @tweets = current_user.related_tweets.sort_by{|t| t.created_at}.reverse! 
end 

class User < ActiveRecord::Base 
    # ... 
    def related_tweets 
     friends_tweets = friends.map{|f| f.tweets} 
     return (tweets.to_a + friends_tweets).flatten 
    end 
    # ... 
end 

또는 다른 솔루션이 모델 트윗에 배열

def index 
    @tweets = Tweet.for_user(current_user).order(cretead_at: :desc) 
end 

작업 할 해달라고하면은

class Tweet < ActiveRecord::Base 
    # ... 
    def self.for_user user 
     me_and_friends = [user.id] + user.friends.map(&:id)  
     where(:user_id => me_and_friends) 
    end 
    # ... 
end 
+0

이것은 완벽합니다, 고마워요! – zhs

+0

한 가지 더 질문합니다. DESC 순서로 created_at에 의해 정렬되도록하고 싶다면 모델에서 그렇게할까요? 다시 한 번 감사드립니다 – zhs

+0

컨트롤러에서 주문하는 것이 더 좋습니다. 이렇게하면 모델에서 메소드를 오염시키지 않고 'created_at'또는 다른 속성을 사용하여 더 많은 장소에서 매번 사용할 수 있습니다. – Nermin

1

당신은 tweetsusers 사이에있는 관계를 보여주지 않았다,하지만 난 당신을 생각이있어 사용자가 많은 트윗을 가지고있다.

@tweets = Tweet.where(user_id: [current_user.id].concat(current_user.user_friendships.all.map(&:id))) 
+0

흠, 이것은 단지 아직 내 짹짹을 반환. 모델의 코드를 추가하면 도움이 될까요? 원래 게시물에 추가하겠습니다. – zhs

+0

미안 해요, 나는 떨어져 있었지만, 지금 당신은 이미 대답을 보았습니다 :) –

0

당신은 같은 것을 할 수 있습니다 :

def index 
    @tweet_wall = Tweet.all.where(user_id: current_user.id).where(relationship between user and friend) 
end 

두 번째 조건은 모델에 따라 달라 그런 다음, 당신은 이런 식으로 뭔가를 할 수 있습니다. 모델 사용자의

관련 문제