.build、.create 和 .create 之间的区别!什么时候应该使用它们? [英] The differences between .build, .create, and .create! and when should they be used?
本文介绍了.build、.create 和 .create 之间的区别!什么时候应该使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我最近看到人们越来越多地在他们的控制器中使用 .build
、.create
和 .create!
.与仅使用 .new
并传递 param'd 对象然后 .save
有什么区别?有优点和缺点吗?使用这些其他方法会带来好处吗?
So I've been seeing people using .build
, .create
, and .create!
within their controllers more and more lately. What's the difference from just using .new
and passing the param'd object and then .save
? Are there pros and cons? Does using these other methods offer benefits?
推荐答案
有一些差异,但并不大:
There are a couple differences, but they're not big:
.create
等价于.new
后跟.save
.只是更简洁..create!
等价于.new
后跟.save!
(如果保存失败则抛出错误).它也只是短了一点- 我认为
.build
主要是.new
的别名.它在 Rails 3 中以一种方式运行,在 Rails 中以另一种方式运行 <3.x
.create
is equivalent to.new
followed by.save
. It's just more succinct..create!
is equivalent to.new
followed by.save!
(throws an error if saving fails). It's also just a wee bit shorter- I think
.build
is mostly an alias for.new
. It works one way in Rails 3 and another way in Rails < 3.x
然而,最重要的部分是可以通过关联(has_many
等)调用这些方法以自动链接两个模型.
The most important part, however, is that these methods can be called through an association (has_many
, etc.) to automatically link the two models.
这篇关于.build、.create 和 .create 之间的区别!什么时候应该使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文