Merging a :has_many relationship into one instance

So the problem is that I have an ActiveRecord model that has a :has_many relationship to another model (we'll call this one object), but when I am in the view context I didn't want to have to loop through the object each time to determine which data was being displayed. Object has many attributes (approximately 30) and many are often null for a given instance. So I decided to add a method to my model to loop through all of objects and determine which data should be included. Pretty much the rule was that if there was no data for a particular attribute temporarily save it to a copy of the object and then return that. This is what I came up with.

def object  
    tmp = objects.first
    objects.each {|o| tmp.attributes.each {|key, value| tmp[key] = o[key] if value.blank? && key != 'id'}}
    tmp.freeze
  end

However there was a flaw here. Every time I would view the page all of the data in the objects was getting overwritten with one copy of it. After banging my head on the desk it was realized that tmp[key] = o[key] was actually writing the changes to the database permanently rewriting all of the objects (which still seems counter intuitive to me, because it seems like only the first record should have been the one changing). But the solution was pretty simple. The working method is as follows.

def object  
    tmp = Object.new
    objects.each {|o| tmp.attributes.each {|key, value| tmp[key] = o[key] if value.blank? && key != 'id'}}
    tmp.freeze
  end
comments powered by Disqus