Nice way to merge/copy attributes between two ActiveRecord classes?

ruby, ruby-on-rails-3

Solution

Utilize assign_attributes with the `:without_protection` option.

attributes = object2.attributes.select do |attr, value|
  ObjectModel.column_names.include?(attr.to_s)
end
object1.assign_attributes(attributes, :without_protection => true)

Problem

This has been asked partially before and I found the following clip on how to set a class object's attributes all at once, but it's not possible with Rails because of mass-assignment protection. (e.g. you can't Object.attributes={}) Is there a nice way to merge the attributes from one class into another? ``` object1.attributes = object2.attributes.inject({}){ |h,(k,v)| h[k]=v if ObjectModel.column_names.include?(k); h } ``` Thanks.

Original source