Selecting only one row from child model based on parent model

Below is the relationship between the two models:

class FotoGossip < ActiveRecord::Base
   has_many :uploads
end

class Upload < ActiveRecord::Base
   belongs_to :foto_gossip
end

@latest_uploads = Upload.all(:include => :foto_gossip, :order => "created_at DESC", :limit => 5)  

      

It displays the last 5 photos from the upload model.
But I want to display 5 images from Uploads, order_by created_date DESC, but only 1 image on FotoGossip.
It's sort of a grouping of recent FotoGossip with his one photo from the Uploads model.

0


a source to share


2 answers


This next AR request resolved it.

@latest_uploads = Upload.all(:include => :foto_gossip, :order => "created_at DESC", :limit => 5, :group => :foto_gossip_id)

      



The magic lies in the: group option.

0


a source


I think you can use ActiveRecord :: Base # calculate as in



@latest = Update.maximun(:creted_at,:distinct=>:foto_gossip_id)

      

0


a source







All Articles