2014-06-06 109 views
0

我有一个要复制的对象CartItem。每个CartItem属于Cart在更改某个对象的属性时复制对象

我正在写一个方法,将采取一个旧的订单,并复制其所有cart_items并将其放置在当前的购物车。

order.add_items_to_cart(current_cart, current_user)

Order.rb

def add_items_to_cart(cart, cart_user) 
    cart.update_attributes(merchant_id: self.merchant_id) 

    self.cart_items.each do |ci| 
    new_cart_item = ci.dup 
    new_cart_item.save 
    new_cart_item.update_attributes(cart_id: cart.id, cart_user_id: cart_user.id) 
    end 
end 

目前,我有以上。有没有更好的方法来改变和改变一行中的属性?

回答

0

如果只复制属性,但关联对你来说可以,那么你的表现很好。 http://apidock.com/rails/ActiveRecord/Core/dup

但是,我建议你使用assign_attributes,所以你只会做一个查询。

def add_items_to_cart(cart, cart_user) 
    cart.update_attributes(merchant_id: self.merchant_id) 

    self.cart_items.each do |ci| 
    new_cart_item = ci.dup 
    new_cart_item.assign_attributes(cart_id: cart.id, cart_user_id: cart_user.id) 
    new_cart_item.save 
    end 
end 

编辑:

制作方法车#重复,它返回你所需要的

class CartItem  

    ... 

    # returns copy of an item 
    def duplicate 
    c = Cart.new cart_id: cart.id, cart_user_id: cart_user.id 
    # copy another attributes inside this method 
    c 
    end 
end 


# And use it 
self.cart_items.each do |ci| 
    new_card_item = ci.duplicate 
    new_card_item.save 
end 
+0

我要复制的属性,也是协会,但我要指出的协会一个不同的对象。 – Huy

+0

你可以创建方法'CartItem#duplicate',它返回你所需要的。我已经更新了上面的代码。 – Zhomart