Rails克隆复制或复制

我有一个嵌套的表单,一旦我保存,我希望能够单击显示页面上的链接来复制或克隆该表单并打开一个新表单。 从那里我应该能够进行编辑(比如新的id)并保存为新记录。 我见过一些像deep_cloneable gem这样的例子,但我不知道如何实现它。 我认为这应该很简单,但我只是不明白把东西放在控制器和show视图中的位置。

如果要复制activeRecord对象,可以使用其属性创建新的对象

您可以在控制器中执行一个可以在链接上调用的操作,

def create_from_existing @existing_post = Post.find(params[:id]) #create new object with attributes of existing record @post = Post.new(@existing_post.attributes) render "your_post_form" end 

我发现这些答案有点难以理解。 一个答案显示:

 @post = Post.new(@existing_post.attributes) 

这将无法工作,因为它也将传递id和时间戳值。 我用.dup来解决这个问题,并在答案中表明了这一点。

以下是我从现有项目中创建新项目的方法。

该模型适用于Product,控制器Products_Controller.rb。 我们将向控制器添加一个名为COPY的新动作,我们将从现有产品的SHOW视图链接到它,并渲染一个已填充的新视图,可以进行编辑和保存。

首先,我们在routes.rb中为复制操作创建一个路由

 resources :Products do member do get 'copy' end end 

然后在Products_controller.rb中进行复制操作

  def copy @source = Product.find(params[:id]) @product = @source.dup render 'new' end 

现在我们需要添加一个链接到SHOW视图来调用我们的复制操作。

 <%= link_to "copy", copy_product_path(params[:id]) %> 

这对我有用。 我希望它适合你,答案很简单,可以遵循。

 class Foo < ActiveRecord::Base def self.clone_from(parent) parent = find(parent) unless parent.kind_of? Foo foo = self.new foo.attributes = parent.attributes # if you want to also clone a habtm: foo.some_association_ids = parent.some_association_ids # etc. foo end end class FoosController < ApplicationController def clone foo = Foo.clone_from(params[:id]) respond_with(foo) end end 

另外值得一提的是模型上的dup方法。 它创建了一个包含所有属性和传出关系的副本,但将id设置为nil 。 像这样(借用Naren Sisodiya的代码):

 def create_from_existing @existing_post = Post.find(params[:id]) #create new object with attributes of existing record @post = @existing_post.dup render "your_post_form" end