在Rails中具有一对多关系的重复实体

huangapple go评论61阅读模式
英文:

Duplicate entity with one to many in rails

问题

这是一个有些新手问题。

我在Rails中有一个一对多的关系,比如项目(Project)与多个任务(Tasks)的关系。
我想要为用户提供重新创建项目和任务的能力,比如在员工入职后再使用相同的任务。所以在每个项目记录上,添加一个“复制”按钮。当点击时,我将创建一个新的项目,其中某些属性已更改,并重新创建该项目的所有任务。

我的问题很一般,我应该在哪里做以及如何做?我知道Rails提供了一个*.dup函数。这应该放在模型(Model)中吗?还是控制器(Controller)中?Rails的处理方法是什么?

谢谢!

英文:

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!

答案1

得分: 0

关于deep_cloneable是什么?

> deep_clone方法支持通过传递选项哈希指定的一些选项。如果没有选项,行为与ActiveRecord的dup方法相同。

project.deep_clone(include: :tasks)
英文:

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)

答案2

得分: 0

这将是Project类中的一个好方法。

class Project
  has_many :tasks

  def duplicate
    p = Project.create(name: "复制自#{ name }")

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

    p
  end

然后,要使用它,

new_project = existing_project.duplicate
英文:

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

huangapple
  • 本文由 发表于 2023年1月9日 06:27:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75051708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定