搜索并比较ActiveRecord属性以查找最大值

时间:2010-05-04 03:44:48

标签: ruby-on-rails ruby

我的模型看起来像是:

my_diet = Diet.new
my_diet.food_type_1 = "beef"
my_diet.food_type_1_percentage = 40
my_diet.food_type_2 = "carrots"
my_diet.food_type_2_percentage = 50
my_diet.food_type_3 = "beans"
my_diet.food_type_3_percentage = 5
my_diet.food_type_4 = "chicken"
my_diet.food_type_4_percentage = 5

我需要找到哪个food_type的百分比最高。到目前为止,我已经尝试从attibutes和百分比中创建一个哈希值,然后对哈希值进行排序(见下文),但感觉必须有一个更清晰的方法来实现它。

  food_type_percentages = { :food_type_1 => my_diet.foo_type_percentage_1_percentage.nil? ? 0 : my_dient.food_type_1_percentage,
                            :food_type_2 => my_diet.foo_type_percentage_2_percentage.nil? ? 0 : my_dient.food_type_2_percentage,
                            :food_type_3 => my_diet.foo_type_percentage_3_percentage.nil? ? 0 : my_dient.food_type_3_percentage,
                            :food_type_4 => my_diet.foo_type_percentage_4_percentage.nil? ? 0 : my_dient.food_type_4_percentage
  }
  food_type_percentages.sort {|a,b| a[1]<=>b[1]}.last

有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

要在数据库中找到现有行的列之间的最大值,请执行以下操作:

d = Diet.first(:select => "*, GREATEST(
                 food_type_1_percentage, 
                 food_type_2_percentage, 
                 food_type_3_percentage, 
                 food_type_4_percentage) AS top_food_type_percentage,
       CASE GREATEST(
                 food_type_1_percentage, 
                 food_type_2_percentage, 
                 food_type_3_percentage, 
                 food_type_4_percentage)
         WHEN food_type_1_percentage THEN food_type_1
         WHEN food_type_2_percentage THEN food_type_2
         WHEN food_type_3_percentage THEN food_type_3
         WHEN food_type_4_percentage THEN food_type_4
       END AS top_food_type")


d.top_food_type # carrots
d.top_food_type_percentage # 50

如果您想在当前模型实例中找到顶级食物类型,那么

class Diet < ActiveRecord::Base

  def top_food_type
    send(top_food_type_col)
  end

  def top_food_type_percentage
    send("#{top_food_type_col}_percentage")
  end

  FOOD_TYPE_COL = %w(food_type_1 food_type_2 food_type_3 food_type_4)

  def top_food_type_col
    @top_food_type_col ||= FOOD_TYPE_COL.sort do |a, b| 
     send("#{a}_percentage") <=> send("#{b}_percentage")
    end.last
  end
end

现在您可以执行以下操作:

d = Diet.new
....
....
....
d.top_food_type # carrots
d.top_food_type_percentage # 50

答案 1 :(得分:0)

我假设food_percentage是列

如果你只是想找出ref this

Diet.maximum('food_percentage') # gives 50

或者您希望完整记录使用此

Diet.find(:first, :order=> 'food_percentage DESC', :limit=>1)
相关问题