I am making a Twitter clone using rails 4 just for practice. When a user is logged in, on the timeline I only want to display tweets of the people they follow (friends) and their own tweets in DESC order. I'm using tweets#index as my timeline. Currently I am displaying all tweets in the database to the user:
def index
@tweets = Tweet.all.order("created_at DESC")
end
I added an instance variable called @user_friendships that contains the current logged in users friends, witch I can then iterate through and access their tweets. Here is what it now looks like:
def index
@user_friendships = current_user.user_friendships.all
@tweets = Tweet.all.order("created_at DESC")
end
I don't want to loop through user_friendships and grab it's friend and then tweets in the view as well as loop through the current_users tweets.
In the controller, I want to have one instance variable that contains the tweets of both the current_user and each friends tweets in user_friendships...so in the View I only have to iterate through the new array.
Model Code
### 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