Created
January 14, 2015 23:27
-
-
Save e3matheus/15e25d9721e94acccae4 to your computer and use it in GitHub Desktop.
Revisions
-
e3matheus renamed this gist
Jan 14, 2015 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
e3matheus created this gist
Jan 14, 2015 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,33 @@ 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