问题
Following is the association between 2 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 latest 5 photos from Upload model.
But, I want to display 5 images from Uploads, order_by created_date DESC but only 1 image per FotoGossip.
Its something like grouping the recent FotoGossip with its one photo from Uploads model.
回答1:
I think you can use ActiveRecord::Base#calculate like in
@latest = Update.maximun(:creted_at,:distinct=>:foto_gossip_id)
回答2:
This following AR query solved 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.
来源:https://stackoverflow.com/questions/857350/selecting-only-one-row-from-child-model-based-upon-the-parent-model