开发者

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:

  • Netbeans 6.9 RC2
  • JRuby 1.5.0

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_produ开发者_高级运维cts = 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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜