I would appreciate it if you could answer. Thank you!

I want to achieve

I want to display all tweets of the users I follow on the top page in chronological order.

Current status

It is possible to display all tweets of the users who are following on the top page, but the order is the order of user registration.
For example
1. User1 posts tweet1
2. User2 posts tweet2
3. User1 posts tweet3

Even if you post in the order of 1 to 3, the order in which they are displayed is from the top
2. User2 posts tweet2
3. User1 posts tweet3
1. User1 posts tweet1
Will be.

Corresponding source code
class Relationship</pre>
<pre><code data-language = "controller">#relationships
class RelationshipsController</pre>
<pre><code data-language = "view">#relationships #index
<% @ followingings.each do | following |%>
<% following.tweets.order ("created_at DESC"). each do | tweet |%>
What I tried
  def index
    @followings = current_user.try (: followings) .order ("created_at DESC")

Same result + When logging out, the following error appears

NoMethodError in RelationshipsController # index
undefined method `order'for nil: NilClass

That's it. I would appreciate your advice.

  • Answer # 1

    The tweet has a user_id column and can be filtered by current_user.followings

    followings = current_user.followings
    @tweets = Tweet.where (user: followings) .order (created_at: "desc")

    How to associate and get

    has_many: timeline,: through =>: followings, source: "tweets"
    @tweets = current_user.timeline.order (created_at: "desc")

    I managed to write the one below. I can't explain how it works.
    I'm checking with a small sample, so I'm sorry if I make a mistake.

    Both have the same result, but they execute different SQL.
    It depends on the amount of data (and maybe even the MySQL settings), so I can't say which one is better.