在 Rails 3 中组合记录

发布于 2024-11-11 15:28:54 字数 1029 浏览 1 评论 0原文

我有 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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

热情消退 2024-11-18 15:28:54

假设您的事务可以属于产品或属于服务,那么听起来多态关联是您最好的选择,并且可能会使您现有的问题变得更加简单。

查看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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文