0

I have an ActiveRecord object (x) with some records in it.

First, I want to create an empty recordset (y). Something like :

y = x.class.new  EDIT: -or- y = ActiveRecord::Relation.new

Second, I want to copy (duplicate) a record from x to y. Something like :

y << x.first.dup

How can I do that ? (Is it possible ?)

I have an error on the first line, saying that an argument is missing. I'm able to make new String with this method, but not with ActiveRecord objects.

# x.class : ActiveRecord::Relation::ActiveRecord_Relation_Analysis
x = Analysis.where(category: 6) 

# In a helper ...
# The x object is not always an Analysis.  So I must use its class 
y = x.class.new 

Error on the last line :

ArgumentError: wrong number of arguments (0 for 1+)
        from .. /activerecord-4.0.1/lib/active_record/relation/delegation.rb:76:in `new'
Eric Lavoie
  • 5,121
  • 3
  • 32
  • 49
  • Answer can be found in answer for the same question http://stackoverflow.com/questions/60033/what-is-the-easiest-way-to-duplicate-an-activerecord-record – Khaled May 13 '14 at 23:06
  • 1
    Is `x` an `ActiveRecord::Relation` object? I.e. is `x` the result of an `ActiveRecord` query like for example `Post.where(...)`? – Patrick Oscity May 13 '14 at 23:13
  • @p11y yes it is. It's in fact an ActiveRecord::Relation, results of a query to the database. – Eric Lavoie May 14 '14 at 12:16
  • Not exactly. I looked at the question http://stackoverflow.com/questions/60033/what-is-the-easiest-way-to-duplicate-an-activerecord-record and all its answers. I didn't find how to create the empty set. I just want to copy few records from the set in an empty one. – Eric Lavoie May 14 '14 at 12:39

1 Answers1

2

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
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168