Allow saving of nested objects
Inspired by http://weblog.jamisbuck.org/2007/1/11/moving-associated-creations-to-the-model
1 2 ActiveRecord::Base::ClassMethods.class_eval do 3 # Allows set data it nested way from form for has_one and belongs_to associations 4 # add <tt>association_data=</tt> method that asset Hash 5 # Example: <tt>allow_data_update_for :place</tt> to allow saving input fields with names like "organization[place_data][address]" 6 # Inspired by http://weblog.jamisbuck.org/2007/1/11/moving-associated-creations-to-the-model 7 def allow_data_update_for(association) 8 define_method "#{association}_data=" do |data| 9 if self.send(association) 10 self.send(association).attributes = data 11 instance_eval "@update_#{association}_on_save = true" 12 else 13 self.send("build_#{association}", data) 14 end 15 end 16 before_update do |obj| 17 obj.send(association).save if obj.instance_variable_get("@update_#{association}_on_save") 18 end 19 end 20 end