Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 598
dubmojo Avatar asked Apr 11 '12 19:04

dubmojo


1 Answers

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)
like image 107
Matt Huggins Avatar answered Sep 29 '22 02:09

Matt Huggins