我有一个名为@jdc_array
的实例变量,对检查的内容是这样的:采用注射法,总结数组的情况下轨
"[#<ActiveRecord::Associations::CollectionProxy [#<JobDeliveryCost id: 13, job_id: 53, delivery_cost_id: 1, cost_per_unit: 50.0, quantity: 3, timing: \"install\", created_at: \"2014-07-23 15:20:34\", updated_at: \"2014-07-23 15:20:34\">, #<JobDeliveryCost id: 15, job_id: 53, delivery_cost_id: 1, cost_per_unit: 50.0, quantity: 5, timing: \"install\", created_at: \"2014-07-23 15:57:45\", updated_at: \"2014-07-23 15:57:45\">, #<JobDeliveryCost id: 18, job_id: 53, delivery_cost_id: 1, cost_per_unit: 44.0, quantity: 1, timing: \"breakdown\", created_at: \"2014-07-23 18:27:20\", updated_at: \"2014-07-23 18:27:20\">, #<JobDeliveryCost id: 19, job_id: 53, delivery_cost_id: 1, cost_per_unit: 22.0, quantity: 1, timing: \"install\", created_at: \"2014-07-23 18:27:28\", updated_at: \"2014-07-23 18:27:28\">, #<JobDeliveryCost id: 20, job_id: 53, delivery_cost_id: 1, cost_per_unit: 3.0, quantity: 1, timing: \"install\", created_at: \"2014-07-23 18:28:45\", updated_at: \"2014-07-23 18:28:45\">]>, nil]"
我要总结的cost_per_unit:
所有的情况下,所以我创造了这个方法
def calculate_delivery_total(array)
array.map(&:cost_per_unit).inject(0, &:+)
end
并调用像这样的方法:
def index
if get_deliverable
@jdc_array=(@job.job_delivery_costs.any? ? [@job.job_delivery_costs,@new_delivery] : [@new_delivery])
@new_delivery = @deliverable.job_delivery_costs.build
end
set_job_delivery_cost
@total = calculate_delivery_total(@jdc_array)
end
但是,我发现这个错误!!!
formal argument cannot be an instance variable def calculate_delivery_total(@array)
三个问题。为什么我得到这个错误,我该如何解决它?第三,在控制器中做这样的事情是好的形式,还是我应该在别处做,以及如何做?
UPDATE
所以下面SO海报的建议,我改变了方法,这
def calculate_delivery_total(array)
array.map(&:cost_per_unit).inject(0, &:+)
end
,但我仍然得到这个错误
我可以在控制台做到这一点,为什么不会它在这里工作?!
该错误是哪一行? – tadman
这个错误是一个语法错误 - 它与'@ jdc_array'的_value_没有任何关系 - 你可能会忘记代码中的某处有'end'。 –
@UriAgassi你现在可以检查吗? – user3868832