Created
January 14, 2015 23:27
-
-
Save e3matheus/15e25d9721e94acccae4 to your computer and use it in GitHub Desktop.
Nested attributes hack
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 characters
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