我在每次调用update
操作时都要更新以下数组:
params['traject_names'].each_with_index do |v, i|
@expense.traject_names[i] = v
end
params['used_vehicles'].each_with_index do |v, i|
@expense.used_vehicles[i] = v
end
params['nb_kms'].each_with_index do |v, i|
@expense.nb_kms[i] = v
end
params['parkings'].each_with_index do |v, i|
@expense.parkings[i] = v
end
params['trains'].each_with_index do |v, i|
@expense.trains[i] = v
end
params['taxis'].each_with_index do |v, i|
@expense.taxis[i] = v
end
params['metros'].each_with_index do |v, i|
@expense.metros[i] = v
end
params['meals'].each_with_index do |v, i|
@expense.meals[i] = v
end
params['hotels'].each_with_index do |v, i|
@expense.hotels[i] = v
end
params['natures'].each_with_index do |v, i|
@expense.natures[i] = v
end
params['amounts'].each_with_index do |v, i|
@expense.amounts[i] = v
end
params['o_ns'].each_with_index do |v, i|
@expense.o_ns[i] = v
end
params['clients'].each_with_index do |v, i|
@expense.clients[i] = v
end
正如你所看到的,它是肮脏和重复的。什么可以让这个更小?
我正在考虑做这样的事情:
['trajects_names', 'used_vehicles', 'nb_kms', etc.].each do |n|
params[n].each_with_index do |v, i|
@expense.n[i] = v
end
end
但我不知道如何通过@expense
访问n
变量。有什么想法吗?
修改/溶液
['traject_names', 'nb_kms'].each do |n|
params[n].each_with_index do |v, i|
@expense.send(n)[i] = v
end
end
我刚刚将params
添加到@ vape的解决方案中。
答案 0 :(得分:1)
您可以使用Object#send方法执行此操作:
['trajects_names', 'used_vehicles', 'nb_kms', etc.].each do |n|
n.each_with_index do |v, i|
@expense.send(n)[i] = v
end
end