問題描述
如何使用 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 sharataka、Vishal、mdiaz00147、7urkm3n)