我想渲染某个类的所有对象,包括调用 Controller 的 index-action 时的最新关联元素。
这是我的聊天室模型的代码。一个聊天室可以有很多订阅者:
class Chatroom < ApplicationRecord
has_many :subscribers, dependent: :destroy
end
当用户访问起始页面时,他应该看到所有聊天室和每个聊天室最近创建的订阅者(不是最近关联的)。
我的 Controller 看起来像这样。它不起作用,我确信有一种方法可以以某种方式限制
(:include => :subscribers)
命令左右:class ChatroomsController < ApplicationController
# GET /chatrooms
def index
@chatrooms= Chatroom.all.includes(Subscriber.where("subscriber.created_at < ?", Time.now).order('created_at DESC').first)
render json: @chatrooms
end
end
我很难找到有关如何选择正确订阅者对象的解决方案。你能帮我解决这个问题吗?
最佳答案
如果您想急切加载最新的相关 每个聊天室的订阅者,您可以添加has_one
与您的Chatroom
的范围相关联模型:
class Chatroom < ApplicationRecord
has_many :subscribers, dependent: :destroy
has_one :latest_subscriber, -> { order(created_at: :desc) }, class_name: 'Subscriber'
end
并包括它:
@chatrooms = Chatroom.includes(:latest_subscriber).all
When a user visits the starting page, he should see all chatrooms and the most recently created subscriber (not the most recently associated).
加载一个,最近创建的订阅者,无关联 对于特定的聊天室,您应该使用单独的查询。例如:
@most_recent_subsciber = Subscriber.order(created_at: :desc).first
然后只需构建由聊天室数组组成的 JSON 响应,以分别呈现它们,同时还能够为每个聊天室呈现最新的订阅者 (if you include it in
render json
),以及最近创建的订阅者。
关于ruby-on-rails - Rails API - 将 .includes() 结果限制为仅最新创建的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48965585/