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.
class User
include ActiveModel::AttributeAssignment
attr_accessor :email, :first_name, :last_name
end
user = User.new
user.assign_attributes({email: '[email protected]',
first_name: 'Sam',
last_name: 'Smith'})
> user.email
#=> "[email protected]"
> user.first_name
#=> "Sam"

Written byMohit Natoo
Related blogs
- 01Rails 5 Active Record attributes APIDecember 11, 2018 · Abhay Nikam
- 02Rails 5 Create module and class level variablesSeptember 5, 2016 · Abhishek Jain
- 03Rails 5 silences assets logs in dev mode by defaultSeptember 2, 2016 · Midhun Krishna
- 04Rails 5 disables autoloading while app in productionAugust 29, 2016 · Shailesh Kalamkar