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?
So I’ve been seeing people using .build , .create , and .create! within their
Share
There are a couple differences, but they’re not big:
.createis equivalent to.newfollowed by.save. It’s just more succinct..create!is equivalent to.newfollowed by.save!(throws an error if saving fails). It’s also just a wee bit shorter.buildis mostly an alias for.new. It works one way in Rails 3 and another way in Rails < 3.xThe most important part, however, is that these methods can be called through an association (
has_many, etc.) to automatically link the two models.