本文介绍了在Ruby on Rails的构建方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

新建轨道,我跟随在敏捷Web开发使用Rails 3.1中发现的油库项目。一切都很好,直到我在本书中使用的建的方法迷路了。

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方法仅仅是一个创建于表中的行(与表之间的关联),更清洁的方式。但在上述code,我期待code看起来就像是这样的:

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.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?

推荐答案

您误解了建立。这只是,没有什么特别的别名。 https://github.com/rails/rails/blob/959fb8ea651fa6638aaa7caced20d921ca2ea5c1/activerecord/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 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方式将正常工作。但更好的方法是不信任参数。相反,通过先找到在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的构建方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 00:32