views:

80

answers:

2

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_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.

+3  A: 

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.

Chris
b1.attributes function not found!
Zeck
Really? That's odd. Can you post the code for class Book?
Chris
b1 = Admin::TemporaryProduct, p1 = Admin::Product
Zeck
A: 

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.

Vincent Ramdhanie