Rails - 将模型属性作为函数

时间:2015-11-29 00:58:40

标签: ruby-on-rails

我认为这是一个非常基本的问题,但我找不到解决方案。

我有简单的帮助方法:

def getProperNutrientValue(meal)
    result = 0
  if meal.ingredients.empty?
    result
  else
    meal.ingredients.each do |i|
      result += (i.quantity * @meal.products.find(i.product_id).calorific) / 100
    end
    result
  end
end

"热量"是产品型号中的属性。

class Product < ActiveRecord::Base
  has_many :ingredients
  has_many :meals, :through => :ingredients

  validates :calorific, :numericality => true, :allow_nil => true
  validates :water, :numericality => true, :allow_nil => true

我想干掉这个函数,并将属性设置为变量。然后我将可以使用此功能为例如water属性。 所以我想实现这样的目标:

def getProperNutrientValue(meal, attribute)
    result = 0
  if meal.ingredients.empty?
    result
  else
    meal.ingredients.each do |i|
      result += (i.quantity * @meal.products.find(i.product_id).attribute) / 100
    end
    result
  end
end

但当然它不起作用......我该如何解决?

1 个答案:

答案 0 :(得分:2)

您可以使用send(method_name)方法。我不明白使用@meal变量背后的逻辑。无论哪种方式,都有一些改进代码的选项,例如:

def getProperNutrientValue(meal, attribute)
  result = 0
  meal.ingredients.each do |i|
    result += (i.quantity * @meal.products.find(i.product_id).send(attribute).to_i) / 100
  end
  result
end

getProperNutrientValue(meal, :calorific)
相关问题