Rails 5 Attributes from Active Record to Active Model

Mohit Natoo

By Mohit Natoo

on May 17, 2016

This blog is part of our  Rails 5 series.

Before Rails 5, we could use assign_attributes and have bulk assignment of attributes only for objects whose classes are inherited from ActiveRecord::Base class.

In Rails 5 we can make use of assign_attributes method and have bulk assignment of attributes even for objects whose classes are not inherited from ActiveRecord::Base.

This is possible because the attributes assignment code is now moved from ActiveRecord::AttributeAssignment to ActiveModel::AttributeAssignment module.

To have this up and running, we need to include ActiveModel::AttributeAssignment module to our class.

1
2class User
3  include ActiveModel::AttributeAssignment
4  attr_accessor :email, :first_name, :last_name
5end
6
7user = User.new
8user.assign_attributes({email:      '[email protected]',
9                        first_name: 'Sam',
10                        last_name:  'Smith'})
11> user.email
12#=> "[email protected]"
13> user.first_name
14#=> "Sam"
15

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.