Skip to content

Instantly share code, notes, and snippets.

@gil27
Forked from urieljuliatti/create_field.rb
Last active August 29, 2015 14:01
Show Gist options
  • Save gil27/ee734fdffbe2a2b61ac5 to your computer and use it in GitHub Desktop.
Save gil27/ee734fdffbe2a2b61ac5 to your computer and use it in GitHub Desktop.
def create_field(field, field_attributes)
# Multiple values
if is_a_kind_of_collection? field_attributes
self.contact.send "#{field}=", parse_multiple_values(field_attributes, field)
else
parse_single_values field_attributes, field
end
end
private
def is_a_kind_of_collection? field_attributes
field_attributes.is_a?Array or field_attributes.is_a?ActiveRecord::Associations::CollectionProxy
end
def parse_multiple_values field_attributes, field
multiple_values = []
field_attributes.each do |atr|
atr = atr.attributes if field_attributes.is_a?ActiveRecord::Associations::CollectionProxy
atr.reject! {|k,v| k.eql?"id" }
atr.merge!({ :user_id => self.address_book.user.id })
multiple_values << field.singularize.camelize.constantize.new(atr)
end
multiple_values
end
def parse_single_values field_attributes, field
# Single values
field_attributes.reject! {|k,v| k.eql?"id" }
field_attributes.merge!({ :user_id => self.address_book.user.id })
self.contact.send "#{field}=", field.camelize.constantize.new(field_attributes)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment