我目前正在嘗試編寫一個工作人員,必須檢查最新的孩子的狀態,並根據它排隊。例如,發現父母的最大的孩子是在學校Rails ActiveRecord加入最新的孩子的範圍
class Parent
has_many :children
end
class Child
belongs_to :parent
lookup_for :status, symbolize: true
end
目前我的範圍是:
Parent.joins(:children).
where("children.birth_date =
(SELECT MAX(children.birth_date)
FROM children
WHERE children.parent_id = parents.parent_id").
where('children.status = ?', Status[:in_school]').pluck(:parent_id)
好像應該有更好的方式來做到這一點。任何想法
要澄清我找所有誰是最古老的父母的孩子還在上學
當然,你的意思是「parents.id」,而不是:上述模式中的parent_id?我的意思是,你可以這樣做,但接近通用的標準只是主鍵的「id」。 – Rob
我建議你檢查這個stackoverflow後:[http://stackoverflow.com/questions/1313120/retrieving-the-last-record-in-each-group](http://stackoverflow.com/questions/1313120/retrieving - 最後記錄在每個組) –
是啊,一般我同意,但在數據庫中,我們使用它實際上是在像父母形式.parents_id – tuxr