scott.piligrim2018
scott.piligrim2018

Reputation: 129

How do I order a variable in an each loop?

I'm trying to order the "discussions" by date in this loop. However in this loop the "discussions" will be ordered grouped by their parent "channel". How do I ungroup the "discussions" from their "channel" and order them all collectively by date?

        <% current_user.following_channels.each do |channel| %>
                <% channel.discussions.order('created_at desc').limit(40).each do |discussion| %>
                    <%= render partial: "shared/discussions-sub-partial", locals: { discussion: discussion } %>
                <% end %>
        <% end %>

Upvotes: 1

Views: 39

Answers (1)

Tun
Tun

Reputation: 1447

By using channel.discussions you will only have the discussions from that channel only. You should use

current_user.discussions.order('discussions.created at DESC').each do |discussions|
    # do your rendering here
end

user.rb should have something similar to this

# user.rb
class User < ApplicationRecord
    has_many :following_channels
    has_many :discussions, through: :following_channels
end

Upvotes: 3

Related Questions