Skip to content

Instantly share code, notes, and snippets.

@thomsbg
Created November 19, 2015 00:02
Show Gist options
  • Save thomsbg/c74c3176303ab822a663 to your computer and use it in GitHub Desktop.
Save thomsbg/c74c3176303ab822a663 to your computer and use it in GitHub Desktop.
fix_nested_attributes_for_uniqueness.rb
def fix(records, params, matcher)
params = params.deep_dup
records.each do |record|
if p.any? { |attrs| attrs['id'].present? && attrs['id'].to_i == record.id }
next
elsif (new_attrs = p.detect { |attrs| attrs['id'].blank? && attrs[matcher].present? && attrs[matcher].to_i == record[matcher] })
new_attrs['id'] = record.id
else
p << { '_destroy' => true, 'id' => record.id }
end
end
params
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment