I want to render all objects of a certain class, including the latest associated element when, the index-action of a controller is called.
Here is the code for my chatroom-model. A chatroom can have many subscribers:
class Chatroom < ApplicationRecord
has_many :subscribers, dependent: :destroy
end
When a user visits the starting page, he should see all chatrooms and the most recently created subscriber for each chatroom (not the most recently associated).
My controller looks like this. It does not work and I'm cofident, that there is a method to somehow limit the (:include => :subscribers)
command or so:
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
I struggle to find a solution on how to select the correct subscriber object. Could you please help me with this issue?