I want to make a copy of an activerecord record, changing a single field in the process (in addition to the id). What is the simplest way to accomplish this?
I realize I could create a new record, and then iterate over each of the fields copying the data field-by-field - but I figured there must be an easier way to do this...
such as:
@newrecord=Record.copy(:id) *perhaps?*
You can also check the acts_as_inheritable gem.
"Acts As Inheritable is a Ruby Gem specifically written for Rails/ActiveRecord models. It is meant to be used with the Self-Referential Association, or with a model having a parent that share the inheritable attributes. This will let you inherit any attribute or relation from the parent model."
By adding
acts_as_inheritable
to your models you will have access to these methods:inherit_attributes
inherit_relations
Hope this can help you.
To get a copy, use the clone (or dup for rails 3.1) method:
Then you can change whichever fields you want.
ActiveRecord overrides the built-in Object#clone to give you a new (not saved to the DB) record with an unassigned ID.
Note that it does not copy associations, so you'll have to do this manually if you need to.
Rails 3.1 clone is a shallow copy, use dup instead...
If you need a deep copy with associations, I recommend the deep_cloneable gem.
I usually just copy the attributes, changing whatever I need changing:
Since there could be more logic, when duplicating a model, I would suggest to create a new class, where you handle all the needed logic. To ease that, there's a gem that can help: clowne
As per their documentation examples, for a User model:
You create your cloner class:
and then use it:
Example copied from the project, but it will give a clear vision of what you can achieve.
For a quick and simple record I would go with:
Model.new(Model.last.attributes.reject {|k,_v| k.to_s == 'id'}
Use ActiveRecord::Base#dup if you don't want to copy the id