Skip to content

Instantly share code, notes, and snippets.

@e3matheus
Created January 14, 2015 23:27
Show Gist options
  • Save e3matheus/15e25d9721e94acccae4 to your computer and use it in GitHub Desktop.
Save e3matheus/15e25d9721e94acccae4 to your computer and use it in GitHub Desktop.
Nested attributes hack
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment