In Ruby on Rails ActiveRecord, how to make an empty ActiveRecord::Relation object and copy a record from another ActiveRecord::Relation object (full)? [duplicate]

StackOverflow https://stackoverflow.com/questions/23642804

Question

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'
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top