small medium large xlarge

Generic-user-small
08 Feb 2011, 16:58
Stuart J Nettleton (7 posts)

Hi, I would like to clone a product by clicking a link in @app/views/products/index.html.erb@. Some ideas about cloning records are given here that I cannot get to work by including the following in @app/models/product.rb@

alias_method :original_clone, clone
def clone
  product = self.original_clone
end

and a link code in @app/views/products/index.html.erb@ of

<%= link_to 'Clone', product %>

Any help about what to do would be appreciated. Thanks, Stuart

Zim_pragsmall
08 Feb 2011, 20:39
Augusto Rodriguez (9 posts)

Hi Stuart,

This is what I did to implement that

First I added a route in routes.rb to the new feature. I thought that a good url was /products/:id/clone.

   resources :products do 
     put :clone_product, :on => :member
   end

</code>

Then I added the link in /products/index.html.erb to the new “controller method/path” and an extra block to display a message to indicate whether if the clone was successful.

 [...]
  <h1>Listing products</h1>
  <% if notice %>
    <p class="notice"><%= notice %></p>
  <% end %>
[...]
         <%= link_to 'Destroy', product, 
                     :confirm => 'Are you sure?',
                     :method => :delete %><br/>
         <%= link_to 'clone', clone_product_product_path(product), 
                     :confirm => 'Are you sure?',
                     :method => :put %>
[...]

</code>

Then I added the method ‘clone_product’ in products_controller.rb

  def clone_product
     @product = Product.find(params[:id])
     cloned_product = @product.clone
     
     respond_to do |format|
       if cloned_product.save
         format.html { redirect_to(products_path, :notice => "Product '#{@product.title}' was cloned.") }
         format.xml  { head :ok }
       else
         format.html { redirect_to(:back, :notice => "Product '#{@product.title}' couldn't be cloned because #{cloned_product.errors}") }
        format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
       end
     end
   end

</code>

And last I added a custom clone method in products.rb, because I implemented a rule to have unique titles in the product (or maybe the rule was already in the book)

  def clone
    cloned = super
    cloned.title += " copy"
     
    cloned
  end

</code>

I hope this helps (it was a good exercise :D)

Thanks, a

Generic-user-small
08 Feb 2011, 23:17
Stuart J Nettleton (7 posts)

Hi Augusto, wow, that is really neat to use, many thanks! Stuart

You must be logged in to comment