【问题标题】:Ruby on Rails finding the number of items in a cartRuby on Rails 查找购物车中的商品数量
【发布时间】:2012-06-27 15:02:54
【问题描述】:

我在网上商店中有我的 Rails 模型,我使用包含订单项的购物车进行设置。每次点击产品时,都会生成一个具有唯一购物车 ID 的订单项,匹配我为用户会话制作的购物车(此示例来自《Agile Web Development with rails》一书。)

我想计算用户购物车中的商品数量,最好的方法是什么。

这是一个例子

li.each do |line|
     puts li.to_yaml
end

输出 ....

- !ruby/object:LineItem
  attributes:
    id: 14
    product_id: 81
    cart_id: 11
    created_at: 2012-06-27 14:10:09.060706000Z
    updated_at: 2012-06-27 14:10:09.060706000Z
    quantity: 1
---
- !ruby/object:LineItem
  attributes:
    id: 1
    product_id: 2
    cart_id: 6
    created_at: 2012-06-25 18:29:20.726280000Z
    updated_at: 2012-06-25 18:56:08.690670000Z
    quantity: 2
- !ruby/object:LineItem
  attributes:
    id: 2
    product_id: 4
    cart_id: 6
    created_at: 2012-06-25 18:56:10.014333000Z
    updated_at: 2012-06-25 18:56:10.014333000Z
    quantity: 1

所以,我希望 cart_id 为 6 的用户知道他们有 3 件商品。谢谢。

【问题讨论】:

    标签: ruby-on-rails-3


    【解决方案1】:

    是的,有更好的方法。你的模型是如何设置的?基本上,您希望用户拥有一个购物车和一个购物车 belongs_to 用户。此外,由于 line_item 有一个 cart_id,你可以有 line_item belongs_to cart 和 cart has_many line_items。

    通过这些关联,您可以轻松获得所需的内容:

    cart.line_items.count
    
    user.cart
    
    user.cart.line_items
    

    等等。

    您可以在此处阅读有关 Rails 关联的信息:

    http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

    【讨论】:

      【解决方案2】:

      我用控制台想通了

      选择购物车后,@cart.id = 6current_cart = Cart.find(6) 因为控制台没有使用浏览器会话设置购物车)

      @count = 0
      
      LineItem.all.each do |item|
           if (item.cart_id == @cart.id)
             @count += item.quantity
           end
      end
      

      不过,一定有更好、更有条理的方式……

      【讨论】:

      • 如果你已经像我下面所说的那样建立了关联,你不需要查询所有的 line_items 只是为了检查他们中有多少在购物车中
      【解决方案3】:
      current_cart.line_items.size
      

      如果您在 cart.rb 中有以下内容

        has_many :line_items
      

      -编辑-

      Ops,对不起,你想要数量的总和。

      current_cart.line_items.sum('quantity')
      

      【讨论】:

        猜你喜欢
        • 2015-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-27
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 2020-08-30
        相关资源
        最近更新 更多