我认为这确实是一个基本问题,但我找不到解决方案。
我有简单的帮助方法:
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
我想干燥这个函数,并将属性设置为变量。然后我将可以使用这个函数来例如水属性。 所以我想实现这样的目标:
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
但是它当然不起作用...我该如何修复它?
最佳答案
您可以使用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)
关于ruby-on-rails - Rails - 模型属性作为函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33978222/