Suppose you have an ActiveRecord model Model
, and a collection of Records x
that was obtained from a previous query and is of type ActivRecord::Relation
. Then you can duplicate the entire list this way:
y = x.map(&:dup)
note that this will set the id attribute to nil
, you will still have to create
the records to persist them to the database:
y.map(&:save)
or in one go:
x.each do |record|
record.dup.save
end
If you want to clone just a single record, you don't need the collection wrapped around and you can just do:
clone = x.first.dup
clone.save