Rails API - 将 .includes() 结果限制为仅最新创建的记录
Rails API - limit .includes() results to only the latest created record
我想渲染某个class的所有对象,包括最新的关联元素,当调用一个控制器的index-action时
这是我的聊天室模型的代码。一个聊天室可以有很多订阅者:
class Chatroom < ApplicationRecord
has_many :subscribers, dependent: :destroy
end
当用户访问起始页时,他应该看到所有聊天室和每个聊天室最近创建的订阅者(不是最近关联的)。
我的控制器看起来像这样。它不起作用,我很自信,有一种方法可以以某种方式限制 (: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
我很难找到关于如何 select 正确订阅者对象的解决方案。你能帮我解决这个问题吗?
如果您想为每个聊天室预先加载最新的关联订阅者,您可以将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-response,它将包含聊天室数组以分别呈现它们,并能够呈现每个聊天室的最新订阅者 (if you include it in render json
),以及最近创建的订阅者。
我想渲染某个class的所有对象,包括最新的关联元素,当调用一个控制器的index-action时
这是我的聊天室模型的代码。一个聊天室可以有很多订阅者:
class Chatroom < ApplicationRecord
has_many :subscribers, dependent: :destroy
end
当用户访问起始页时,他应该看到所有聊天室和每个聊天室最近创建的订阅者(不是最近关联的)。
我的控制器看起来像这样。它不起作用,我很自信,有一种方法可以以某种方式限制 (: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
我很难找到关于如何 select 正确订阅者对象的解决方案。你能帮我解决这个问题吗?
如果您想为每个聊天室预先加载最新的关联订阅者,您可以将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-response,它将包含聊天室数组以分别呈现它们,并能够呈现每个聊天室的最新订阅者 (if you include it in render json
),以及最近创建的订阅者。