英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论