如何使用 has_many 關聯在 Rails 中排序? (How to sort in rails with has_many association?)


問題描述

如何使用 has_many 關聯在 Rails 中排序? (How to sort in rails with has_many association?)

我有一個帶有用戶、反射和評論的 Rails 應用程序。

用戶有很多反射、組和評論(都屬於用戶)。

反射有很多評論(評論屬於反射)。

用戶應該能夠編寫反射並將其添加到他們所在的組中。

我正在嘗試查找寫入的反射由幾個用戶創建,然後按創建時間(created_at DESC)對它們進行排序。

但是,我無法弄清楚如何使用我已有的關聯來做到這一點。

控制器

  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

模板

<% @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

參考解法

方法 1:

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")

方法 2:

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

方法 3:

Can You try this:

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

(by sharatakaVishalmdiaz001477urkm3n)

參考文件

  1. How to sort in rails with has_many association? (CC BY‑SA 2.5/3.0/4.0)

#has-many #ruby-on-rails






相關問題

Ruby on Rails - Has_many,批量分配問題 (Ruby on Rails - Has_many, Mass Assignment issue)

如何在 hasMany 關聯中使用 CakePHP 2 查找? (How to use CakePHP 2 find in a hasMany association?)

模型沒有像我認為的那樣連接 (Models not connecting as I think they should be)

CakePhp find không tìm nạp hasMany mối quan hệ (CakePhp find doesn't fetch hasMany relationships)

創建關聯後,控制器中的 Ruby on rails NoMethodError (Ruby on rails NoMethodError in controller after create an association)

是否可以以兩種不同的方式關聯模型? (Is it possible to associate models in two different ways?)

在 DetailView yii2 中顯示 HAS_MANY 關係數據 (Display HAS_MANY relation data in DetailView yii2)

Rails - 檢查 has_many 關聯中是否存在記錄 (Rails - check if record exists in has_many association)

在 Rails 中,我可以在另一個模型的模型上設置 has_many 關係嗎? (In Rails, can I set a has_many relation on a model from another model?)

從大於 0 開始計數器緩存 (Starting a counter cache from greater than 0)

如何使用 has_many 關聯在 Rails 中排序? (How to sort in rails with has_many association?)

如何將 ActiveModel::Serializer :has_many 關聯的密鑰格式(即駝峰式)指定為一次性選項(不是全局配置)? (How to specify the key format (i.e. camelcase) for an ActiveModel::Serializer :has_many association as a one-off option (not global config)?)







留言討論