2017-04-18 83 views
0

的最后一个孩子的领域寻找和我有嵌套模型,如(使用PostgreSQL的)Rails的,嵌套的has_many协会,各

class User 
    has_many :pages 
end 

class Page 
    has_many :details 
    belongs_to :user 
end 

class Detail 
    belongs_to :page 
    #It has a column named "count" 
end 

我需要的是说 用户使用id = 1,它有很多的网页与ids = 1,2,3。这些带有ID(1,2,3)的页面有很多细节。 我需要的是让每个页面的最新细节,并从这些最新的细节

我在现在做什么名为“计数”字段的总和

page_ids = current_user.pages.pluck(:id) 
last_followers = Detail.select("DISTINCT ON(page_id) *").where(page_id: page_ids).order("page_id, created_at DESC") 
last_followers.each { |detail| last_sum += detail.counts } 

但事实并非如此看起来不错,找到page_ids,而不是细节,并循环遍历所有这些。

有没有像单一的查询直接的方式,感谢

回答

0

不能完全确定你所求的,但这里有一个尝试:

sum = current_user.pages.map { |page| page.details.last.counts }.sum 
+0

谢谢,那是我所需要的总和。 但是你的查询将要做的是,如果用户说20页而不是打到数据库20次,我想避免。 –