Reputation: 5132
I have a rails app with users, reflections, and comments.
Users have many reflections, groups, and comments (all belong to Users).
Reflections have many comments (comments belongs to reflections).
A user should be able to write a reflection and have it get added to group they are in.
I am trying to find Reflections that are written by a few users and then sort them by when they were created (created_at DESC).
however, I I am not able to figure out how to do this with the associations that I have in place.
Controller
def show
# Find users in the group
@groups = Grouplookup.where(group_id: @group.id)
# Turn that group into a user_array
user_array = []
@groups.each do |group|
user_array << group.user_id
end
# Select users that are in the user_array
@users = User.where(id: user_array)
# HOW DO I SORT THIS @users QUERY BY THE DESC ORDER OF REFLECTIONS??
end
Template
<% @users.each do |user| %>
<u><%= user.email %></u>
<br>
<!-- Reflection -->
<% user.reflections.each do |reflection| %>
<%= reflection.id %>. <%= reflection.reflection %> (<%= reflection.created_at.strftime("%B %d, %Y") %>)
<br>
<!-- Comment -->
<% reflection.comments.each do |comments| %>
-"<%= comments.comment %>" - <%= user.email %> <br>
<% end %>
<br>
<% end %>
<% end %>
Group.rb
class Group < ApplicationRecord
belongs_to :user
extend FriendlyId
friendly_id :name, use: :slugged
end
User.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
has_many :reflections, -> { order(created_at: :desc) }
has_many :comments
has_many :groups
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
end
Grouplookup.rb
class Grouplookup < ApplicationRecord
end
Upvotes: 0
Views: 617
Reputation: 6311
Can You try this:
array = @groups.pluck(:user_id)
@users = User.includes(:reflections)
.where(id: array)
.order("reflections.created_at DESC")
Upvotes: 0
Reputation: 152
Add a default scope to the reflection model like this and it should do the trick
class Reflections < ApplicationRecord
default_scope order('created_at DESC')
end
Upvotes: 0
Reputation: 7361
You need to use joins then after you can sort records by reflections
@users = User.joins(:reflections).where(id: user_array).order("reflections.created_at DESC").group("users.id")
Upvotes: 1