I have a piece of code here that i really could use some help with refactoring. I need the different methods for adding relational data in a form in rails. The code is taken from http://railscasts.com/episodes/75-complex-forms-part-3, my problem is that i need to have the methods fro both the Material model and the Answer model. So i need the exact same code twice with "materials" replaced by "answers".
It seems this should be solved with some dynamic programming? But I have no experience at all with that.
How is this solved?
after_update :save_materials
after_update :save_answers
def new_material_attributes=(material_attributes)
material_attributes.each do |attributes|
materials.build(attributes)
end
end
def existing_material_attributes=(material_attributes)
materials.reject(&:new_record?).each do |material|
attributes = material_attributes[material.id.to_s]
if attributes
material.attributes = attributes
else
materials.delete(material)
end
end
end
def save_materials
materials.each do |material|
material.save(false)
end
end