Combining Records in Rails 3
I have Transaction objects that are combined in a Cart 开发者_运维技巧object. Some Transaction objects belong_to Products and others belong_to Services. I want to combine similar Transactions when they are added to the cart (ie. update an existing record with new price and quantity information).
Here's what I currently have (untested):
def update_cart
if current_cart.transactions.find(:conditions => [service_id = self.service_id])
@utransaction = current_cart.transaction.find(:conditions => [service_id = self.service_id])
@utransaction.price = @utransaction.price + self.price
@utransaction.save
elsif current_cart.transactions.find(:conditions => [product_id = self.product_id])
@utransaction = current_cart.transactions.find(:conditions => [product_id = self.product_id])
@utransaction.price = @utransaction.price + self.price
@utransaction.quantity = @utransaction.quantity + self.quantity
@utransaction.save
else
nil
end
end
However, I feel that this is very bulky and there is probably a better way of doing it. So, before I go any further, is there any built-in or better ways of updating existing objects in this manner?
Thanks!
Assuming your Transaction can belong_to a Product or belong_to a Service, then it sounds like a Polymorphic association is your best bet, and may make your existing problem much simpler.
Check out the Railscast on Polymorphic Associations.
I think you'll like it and learn a lot.
加载中,请稍侯......
精彩评论