Find ActiveRecord object by maximum field value of a child object?

前端 未结 4 704
太阳男子
太阳男子 2021-02-05 02:31

How can I find the object associated with the results of an ActiveRecord Calculation rather than a value?

For example I have @parent which has many children. I would lik

相关标签:
4条回答
  • 2021-02-05 02:45
    @parent.children.order("value DESC").first
    
    0 讨论(0)
  • 2021-02-05 02:50

    Not sure if this is the most efficient but once you have the maximum value you can pass that along in a hash to get the object

    @maxvalue = @parent.children.maximum(:value)
    @myObject = @parent.children.where(:value => @maxvalue)
    
    0 讨论(0)
  • 2021-02-05 02:55

    This is my personal favorite when it comes to readability, by using ruby's #max_by :

    @parent.children.max_by(&:value)
    
    0 讨论(0)
  • 2021-02-05 03:03
    @parent.children.first(:conditions => {:value => @parent.children.maximum(:value)})
    
    0 讨论(0)
提交回复
热议问题