在 Rails 3 中组合记录
我有 Transaction
对象组合在 Cart
对象中。一些 Transaction
对象 belong_to
Products
和其他 belong_to
Services
。我想在将类似的交易
添加到购物车时合并它们(即使用新的价格和数量信息更新现有记录)。
这是我目前拥有的(未经测试):
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
但是,我觉得这非常庞大,并且可能有更好的方法来做到这一点。那么,在我进一步讨论之前,是否有任何内置或更好的方法以这种方式更新现有对象?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您的事务可以属于产品或属于服务,那么听起来多态关联是您最好的选择,并且可能会使您现有的问题变得更加简单。
查看Railscast 的多态关联。
我想你会喜欢它并学到很多东西。
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.