Search code examples
ruby-on-rails-3duplicatescopyclone

Rails clone copy or duplicate


I have a nested form and once I save, I want to be able to click a link on the show page to copy or clone that form and open a new one. From there I should be able to make edits (like a new id) and save as a new record. I have seen some examples like this deep_cloneable gem, but I have no idea how to implement it. I think this should be simple, but I just don't understand where to put things in the controller and in the show view.


Solution

  • If you want to copy an activeRecord object you can use its attributes to create new one like

    you can have an action in your controller which can be called on link,

    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