Rails活动记录查询:仅在has_many关系中呈现最新的子对象(按子created_at日期排序)

时间:2015-12-17 22:39:53

标签: ruby-on-rails activerecord

父母has_many:孩子。我想呈现每个Parent的最后一个孩子,按孩子的created_at日期排序。我无法弄清楚如何使用有效记录和&导轨。

2 个答案:

答案 0 :(得分:2)

尝试:

public class CertTest {

    public static final String cert = "-----BEGIN CERTIFICATE-----\n<CERT_DATA>\n-----END CERTIFICATE-----";

    public static void main(String[] args){
        try {
            X509Certificate myCert = (X509Certificate)CertificateFactory
                     .getInstance("X509")
                     .generateCertificate(
                                       // string encoded with default charset
                    new ByteArrayInputStream(cert.getBytes())
                     );
            System.out.println(myCert.getNotAfter());

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

youngest_kids = Parent.includes( :children ).map { |parent| parent.children.last }.compact 删除了compact的{​​{1}},而nil没有parent

答案 1 :(得分:0)

Parents.all.each do |parent|
  parent.children.order(:created_at).last
end