【问题标题】:What does that line of code do?那行代码有什么作用?
【发布时间】:2010-12-06 22:01:17
【问题描述】:

当他在模型中展示这种方法时,我正在阅读使用 Rails 4Th 编辑的敏捷 Web 开发一书:

def add_line_items_from_cart(cart)
    cart.line_items.each do |item|
      item.cart_id = nil
      line_items << item
    end
  end

这是解释:

*对于我们从购物车转移到订单的每件商品,我们需要做两件事。首先,我们将 cart_id 设置为 nil,以防止我们销毁购物车时物品会变得糟糕。然后我们将商品本身添加到订单的 line_items 集合中。请注意,我们不必对各种外键字段做任何特殊处理,例如将订单项行中的 order_id 列设置为引用新创建的订单行。 Rails 使用我们添加到 Order 和 LineItem 模型中的 has_many 和 belongs_to 声明来为我们编织。将每个新的行项目附加到 line_items 集合中,将密钥管理的责任交给 Rails。*

谁能解释一下这行简单的代码 line_items

感谢您的关注 西蒙娜

【问题讨论】:

    标签: ruby ruby-on-rails-3


    【解决方案1】:

    有人能解释一下这行简单的代码line_items &lt;&lt; item 是如何完成所有这些工作的吗?

    那条线并没有做所有这些。

    最好这样读:

    def add_line_items_from_cart(cart)   #<-- For each item that we transfer from the cart to the order we need to do two things
        cart.line_items.each do |item|
          item.cart_id = nil             #<-- First we set the cart_id to nil in order to prevent the item from going poof when we destroy the cart.
          line_items << item             #<-- Then we add the item itself to the line_items collection for the order
        end
    end
    

    剩下的:

    请注意,我们不必对...等做任何特别的事情

    是关于框架做什么的信息。因此,描述对应于整段代码,而不仅仅是那一行。

    【讨论】:

    • Oscar,您写道:是关于框架功能的信息。因此,描述对应于整段代码,而不仅仅是那一行。您能解释一下该行如何将 order_id 添加到项目中吗?
    【解决方案2】:

    cart.line_items.each do |item| -> 从购物车中取出每个 line_items 并“为它们命名”项目,以便您可以对它们进行更改

    item.cart_id = nil -> 设置物品的card_id为nil

    line_items &lt;&lt; item -> 将商品本身添加到订单的 line_items 集合中

    【讨论】:

      【解决方案3】:

      line_items 是一个列表,line_items &lt;&lt; item 将一个项目添加到该列表中。 item.cart_id = nil 清除商品的购物车 ID,以防它与其他购物车相关联。

      【讨论】:

        【解决方案4】:

        书上已经说过 It's Rails 的工作,line_items、belongs_to 和 has_many 是 Rails 需要的所有东西。在 Rails 内部,它帮助我们更新 line_item.order_id。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-24
          • 2016-06-03
          • 1970-01-01
          • 2011-07-04
          相关资源
          最近更新 更多