Zeck
Zeck

Reputation: 6579

How to copy or clone model?

I have a model Book with attributes id, name, price. I have an instance of Book:

b1 = Book.new
b1.name = "Blah"
b1.price = 12.5
b1.save

I would like to copy b1, create another instance of the Product model. I'm tryid p1=b1.clone then p1.save but it didn't work. Any idea?

And my environment is:

EDITED: My TemporaryProduct model:

class Admin::TemporaryProduct < ActiveRecord::Base

  def self.update_from_web_service(web_service_url)
    response = HTTParty.get(web_service_url)
    response["webServiceResult"]["product"].each do|element|
      unless exists? :orignal_product_id => element['id']
        create!(
          :name => element['name'],
          :price => element['price'],
          :amount => element['amount'],
          :description => element['description'],
          :orignal_product_id => element['id'],
          :image => element['image'],
          :shop_account_number => element['shopAccountNumber'],
          :unit => element['unit']
        )
      end
    end
  end
end

Product is create action:

  def create
    @temporary_products = Admin::TemporaryProduct.find_all_by_orignal_product_id(params[:product])
    @product = Admin::Product.new(@temporary_products.attributes)
    # @product = @temporary_products.clone
    respond_to do |format|
      format.html { redirect_to(admin_products_url, :notice => 'Admin::Product was successfully created.') }
    end
  end

I want to clone all b1's attributes to p1 model.

Upvotes: 2

Views: 3895

Answers (3)

Foram
Foram

Reputation: 623

You can make duplicate record using dup in rails For Example,

b1 = Book.create(name: "example", price: 120)
b1.save
duplicate_record = b1.dup
duplicate_record.save!

or you can create first new record and then make a duplicate

Hope this is useful for you.

Upvotes: 3

Chowlett
Chowlett

Reputation: 46675

I think you want:

b2 = Book.create(b1.attributes)

Edit: Given your create action above, I think what you want to do is change the line which starts @product to

@temporary_products.each {|tp| Admin::Product.create(tp.attributes)}

That will create a new Product object for each TemporaryProduct object, using the same attributes as the TemporaryProduct. If that's not what you want, let me know.

Upvotes: 9

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

If by didn't work you mean that there is no new record in the database then you probably want to set the id of p1 to null before you save. If the clone has the same id as the original then it would appear to represent the same object.

Upvotes: 0

Related Questions