我有一个带有属性 id、name、price 的模型 Book。我有一个书的实例:
b1 = Book.new
b1.name = "Blah"
b1.price = 12.5
b1.save
我想复制 b1,创建 Product 模型的另一个实例。我是 tryid p1=b1.clone 然后是 p1.save 但它没有用。有什么想法吗?
我的环境是:
- Netbeans 6.9 RC2
- JRuby 1.5.0
已编辑: 我的临时产品模型:
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
产品是创建 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
我想将 b1 的所有属性克隆到 p1 模型。
最佳答案
我想你想要:
b2 = Book.create(b1.attributes)
编辑:
鉴于您上面的 create
操作,我想您要做的是将 @product
开头的行更改为
@temporary_products.each {|tp| Admin::Product.create(tp.attributes)}
这将为每个 TemporaryProduct
对象创建一个新的 Product
对象,使用与 TemporaryProduct
相同的属性。如果这不是您想要的,请告诉我。
关于ruby-on-rails - 如何复制或克隆模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3036447/