Kim
Kim

Reputation: 2156

ruby on rails - cloning an entry along with its associated models data

I really need some help concerning cloning/duplicating an entry along with its associated data. I have a submission which has associated submitter's details, notes + other associated information found in several tables.

I tried using the code below:

  def duplicate1
    submission_to_dup = Submission.find(params[:id])
    new_submission = Submission.create(submission_to_dup.attributes)
    end

    def duplicate2
    new_submission = Submission.create(Submission.find(params[:id]).clone);
    end

But it seems that both methods do a shallow copy of its parent object, without an ID or any associations.

Is there any way of duplicating a record along with its associated data?

Thanks a lot in advance for your precious help :)

Upvotes: 1

Views: 314

Answers (1)

Jason Lewis
Jason Lewis

Reputation: 1314

Duplicating an object in ActiveRecord will never clone :id, b/c it's a unique primary key. And since that primary key should be the foreign key in the associations of that object, you're going to lose those as well. The only way I can think of to create a duplicate record is to do something like:

def duplicate_record
  rec = Submission.find(params[:id])
  new = Submission.new(:attr => rec.attr)
  if new.save
    new.update_attributes(:nested_attr => {:attr => rec.nested_attr.attr})
  else
    something else
  end
end

But I can't think why you'd want to. I spend most of my time trying to keep duplicate records out of my databases.

Anyway, hope this helps.

Upvotes: 1

Related Questions