41

New to rails and I'm following the Depot project found in the Agile web development with rails 3.1. Everything was fine until I got lost when the book used the "build" method.

@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.line_items.build(product: product)

My google searches led me to understand that the .build method is just a cleaner way to create a row in the table (with association between tables). But on the code above, I was expecting the code would look like something like this:

@line_item = @cart.line_items.build(product_id => params[:product_id])

I don't understand why the author had to store the whole row of products( product = Product.find(params[:product_id])) instead of just getting the product_id...

Is there more to it than what I can understand?

4

2 回答 2

80

你误会了build。它只是 的别名new,没什么特别的。https://github.com/rails/rails/blob/959fb8ea651fa6638aaa7caced20d921ca2ea5c1/activerecord/lib/active_record/relation.rb#L84

build不会在数据库中“创建”记录,只需在内存中创建一个新对象,以便视图可以获取该对象并显示某些内容,尤其是对于表单。

对于你的第二个问题,是的,你的 id 作曲方式也可以。但更好的方法是不信任 param。相反,首先通过在 db 中查找来验证它。

于 2013-11-04T05:34:06.863 回答
1

我要继续说你是完全正确的。任何一种方法都有效并且会做同样的事情,但是您的版本使用 just:product_id更有效并且需要更少的数据库查询。也就是说,如果您product稍后在代码中需要该变量或稍后调用该特定行项目,product.{something}那么它可能不需要在此时通过 id 获取它。

但是,我个人更喜欢只设置:product_id,我认为没有理由先找到对象。

于 2013-11-04T04:52:38.250 回答