# Active Record associations performance

**URL:** <https://www.ruby-forum.com/t/active-record-associations-performance/177315>\
**Category:** Rails\
**Created:** [October 14, 2009, 8:17pm UTC](https://www.ruby-forum.com/t/active-record-associations-performance/177315 "2009-10-14T20:17:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![S\_ai\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/57b2e6/32.png) [@S\_ai\_S](https://www.ruby-forum.com/u/S_ai_S)\
**Post date:** [October 14, 2009, 8:17pm UTC](https://www.ruby-forum.com/t/active-record-associations-performance/177315/1 "2009-10-14T20:17:27Z")

</div>

Hi,

I’m running into a memory performance issue with Active Record  
associations.  
I’m tinkering with Redmine, a rails-based project management  
application. The central model in the application is ‘Project’ which  
associates via has\_many to model Issue. One of the things you can do  
with Projects is copy them. In a nutshell, copy is implemented like  
this (in class Project):  
def copy(other\_project)  
other\_project.issues.each do |other\_issue|  
self.issues \<\< other\_issue.copy  
end  
self.save  
end

The problem is that issues are themselves complex objects, and for a  
project with many issues (several thousand), self.issues grows to the  
point of exhausting memory and swap on the box, effectively making a DOS  
attack out of this function. So the question is, is there an idiomatic  
Active Record solution to this problem? Perhaps committing and flushing  
the association list every N adds?

Thanks in advance for any advice.

---

<div class="post-metadata">

**Author:** ![S\_ai\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/57b2e6/32.png) [@S\_ai\_S](https://www.ruby-forum.com/u/S_ai_S)\
**Post date:** [October 14, 2009, 8:52pm UTC](https://www.ruby-forum.com/t/active-record-associations-performance/177315/2 "2009-10-14T20:52:13Z")

</div>

Anton Ivanov wrote:

> Hi,

> this (in class Project):  
> def copy(other\_project)  
> other\_project.issues.each do |other\_issue|  
> self.issues \<\< other\_issue.copy  
> end  
> self.save  
> end

Not tested… just thinking…

Get the link(associative) table that’s used in the many to many  
association and then make sure it has a first class model sitting on top  
of that so you can work with that exclusively…  
Try:

def copy(other\_project)  
other\_project.issues.each do |other\_issue|  
Issue\_projects.new(:issue =\> other\_issue.copy, :project =\>  
self).save();  
end  
end

I believe that the memory requirements will be lower as the self will  
not be adding onto it’s current issues during the copy…

ilan
