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.

Revisions

  1. e3matheus renamed this gist Jan 14, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. e3matheus created this gist Jan 14, 2015.
    33 changes: 33 additions & 0 deletions nested_attributes_hack
    Original 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