Home > Net >  Duplicate entity with one to many in rails
Duplicate entity with one to many in rails

Time:01-09

This is a somewhat newbie question.

I have a one to many relationship in rails, think Project with many Tasks. I want to provide the user with the ability to recreate the Project and Tasks for a new Project (think onboarding an employee and then using the same tasks). So on each project record, add a Duplicate button. When clicked I would create a new project with a few properties changed and recreate all the tasks for that project.

My question is general, what would I do and where? I know rails offers a *.dup function. Would that go in a model? Controller? What is the rails way to approach this.

Thanks!

CodePudding user response:

This would be a good method in the Project class.

class Project
  has_many :tasks

  def duplicate
    p = Project.create(name: "Copy of #{ name }")

    tasks.each do |t|
      p.tasks.create(name: t.name)
    end

    p
  end

Then, to use it,

new_project = existing_project.duplicate

CodePudding user response:

What's about deep_cloneable?

The deep_clone method supports a couple options that can be specified by passing an options hash. Without options, the behaviour is the same as ActiveRecord's dup method.

project.deep_clone(include: :tasks)
  • Related