在 ruby on rails 上构建方法 [英] build method on ruby on rails
问题描述
Rails 新手,我正在关注在 Rails 3.1 的敏捷 Web 开发中找到的 Depot 项目.一切都很好,直到我迷路了,因为这本书使用了构建"方法.
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)
我的谷歌搜索让我明白 .build 方法只是在表中创建行(表之间关联)的一种更简洁的方法.但是在上面的代码中,我希望代码看起来像这样:
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])
我不明白为什么作者必须存储整行产品( product = Product.find(params[:product_id])) 而不是只获取 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?
推荐答案
您误解了 build
.它只是 new
的别名,没什么特别的.https://github.com/rails/rails/blob/959fb69acaced20d921ca2ea5c1activerecord/lib/active_record/relation.rb#L84
You misunderstood build
. It's just an alias of new
, nothing special. https://github.com/rails/rails/blob/959fb8ea651fa6638aaa7caced20d921ca2ea5c1/activerecord/lib/active_record/relation.rb#L84
build
不会在数据库中创建"一条记录,只是在内存中创建一个新对象,以便视图可以使用这个对象并显示一些东西,尤其是对于表单.
build
won't "create" a record in database, just create a new object in memory so that the view can take this object and display something, especially for a form.
对于您的第二个问题,是的,您按 id 编写的方式也可以.但更好的方法是不要相信 param.相反,首先通过在 db 中查找来验证它.
For your second question, yes, your way of composing by id will work as well. But a better approach is not to trust param. Instead, verify it by finding in db at first.
这篇关于在 ruby on rails 上构建方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!