2010-12-06 38 views
0

我读使用Rails 4日的Editon书敏捷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设置为零,以便在我们销毁购物车时防止物品发生呕吐。然后我们将该项目本身添加到订单的line_items集合中。请注意,我们不必对各种外键字段做任何特殊处理,例如将行项目行中的order_id列设置为引用新创建的订单行。 Rails使用我们添加到Order和LineItem模型中的has_many和belongs_to声明来为我们编织。将每个新行项添加到line_items集合中,将密钥管理职责交给Rails。*

有人可以解释一下这个简单的代码行吗?line_items < < item能做所有这些事情吗?

感谢您的关注 西蒙娜

回答

3

有人能解释这个简单的代码line_items << 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 

其余:

我们没有

通知做什么特别......等等等等

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

+0

奥斯卡,你写道:是关于什么框架的信息。因此,描述对应于整段代码,而不仅仅是该行。你能解释一下这条线是如何将order_id添加到项目中的吗? – 2010-12-06 23:24:03

0

line_items是列表,line_items << item添加项目到列表中。 item.cart_id = nil清除了物品的购物车ID,以防与不同的购物车关联。

2

cart.line_items.each do |item| - >需要从车每line_items和“给他们的名字”项,这样就可以对其进行更改

item.cart_id = nil - >设置的项目为零的card_id的

line_items << item - >加上项目本身的line_items集合顺序