Reputation: 2556
I have an ActiveRecord query user.loans
, and am using user.loans.map(&:dup)
to duplicate the result. This is so that I can loop through each Loan
(100+ times) and run several calculations.
These calculations take several seconds longer compared to when I run them directly on user.loans
or user.loans.dup
. If I do this however, all queries user.loans
are affected, even when querying with different methods.
Is there an alternative to .map(&:dup)
that can achieve the same result with faster calculations? I'd like to preserve the relations so that I can retrieve associated records to each Loan
.
Upvotes: 2
Views: 1015
Reputation: 2556
To resolve conflicts with other calls to user.loans
, I wound up using user.loans.reload
in the Presenter
I have for this particular view. This way I was able to continue making calculations directly on Active Record elsewhere(per Daniel Batalla's suggestion), but without the conflicts I mentioned in my original question.
Upvotes: 0
Reputation: 1264
The fastest way you can achieve what you want is making calculations directly on ActiveRecord, this way you would not have to loop through resulting Array.
If you still want to loop through Array elements, maybe you should not use map
to duplicate each Array element. You could use each
instead, which does not affect original Array element. Here is what I think you should do:
def calculate_loans
calculated_loans = Array.new
user.loans.each do |loan|
# Here you make your calculations. For example:
calculated_loans.push(loan.value += 10)
end
calculated_loans
end
This way, you will have original user.loans
elements, and a duplicated Array with calculated_loans
.
Please, let me know if this improve your performance :)
Upvotes: 1