简体   繁体   中英

How to sort in rails with has_many association?

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, II 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

您需要先使用联接,然后才能通过反射对记录进行排序

@users = User.joins(:reflections).where(id: user_array).order("reflections.created_at DESC").group("users.id")

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

Can You try this:

array = @groups.pluck(:user_id)
@users = User.includes(:reflections)
             .where(id: array)
             .order("reflections.created_at DESC")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM