我有一個名爲@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