module Addons module HashNestedAttributes extend ActiveSupport::Concern # My own nested attributes to create a cleaner interface # when sending nested attributes from a javascript app module ClassMethods def accepts_hash_nested_attributes_for relation_name, options = {} relation_class = relation_name.to_s.classify.safe_constantize define_method "#{relation_name}_hash=" do |records| relation_collector = self.send(relation_name).to_a new_ids = records.map {|rec| rec[:id].to_i } old_ids = relation_collector.map(&:id) relation_class.where(:id => old_ids - new_ids).delete_all records.map do |rec| rec = rec.symbolize_keys record = self.send(relation_name).detect { |m| m.id == rec[:id].to_i } if record record.update_attributes(rec) else if !options[:reject_if] || (options[:reject_if].present? && !options[:reject_if].call(rec)) self.send(relation_name).build(rec) end end end end end end end end