Last Updated: May 15, 2019
·
1.582K
· tomaszborowski

Mapping custom data to ActiveRecord objects

When we have to import some data, that attribute names does not match our model's attributes, then we usually write some custom mapping methods. But maybe there is some already implemented solution for that? Answer is: Yes :-)

gem install mapped_attributes

mapped_attributes gem allows you to:

  • map given data to object attributes
  • provide custom mapping definition namespace
  • define multiple mapping for a single attribute
  • map attributes for the has_one and belongs_to relations if you are using nested_attributes

Example

data = {
    'Project Name'  => 'Testing One',
    'Description'   => 'This project is just for test',
    'Task Name'     => 'Get a Job Done',
    'Deadline'      => '2013-02-01'
    'Comments'      => 'Something something dark side'
}
project = Project.new
project.set_mapped_attributes(data)
project.save 

Check out gem repository for details.