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 passig the param'd object and then .save? Are there pros and cons? Does using these other methods offer benefits?
views:
346answers:
2
+3
A:
#create is shorter version of new and save. #create! is throwing exception if validation was not positive.
rkj
2008-12-31 18:25:09
+6
A:
There are a couple differences, but they're not big:
.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 an alias for.new
.
The most important part, however, is that these methods can be called through an association (has_many
, etc.) to automatically link the two models.
zenazn
2008-12-31 18:26:54
I'm selected this one as the most correct answer because of the mention on being able to link the associated models with them - that's an interesting and important difference I think over using .new and .save. Which takes a little extra work. Thanks.
Tim K.
2008-12-31 20:15:34