Selecting only one row from child model based upon the parent model

旧街凉风 提交于 2020-01-16 09:18:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!