Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Allow saving of nested objects

Small extention to allow save data from form with nested data from inputs like "organization[place_data][address]"

Inspired by http://weblog.jamisbuck.org/2007/1/11/moving-associated-creations-to-the-model

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

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets