Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The differences between .build, .create, and .create! and when should they be used?

There are a couple differences, but they're not big:

  1. .create is equivalent to .new followed by .save. It's just more succinct.
  2. .create! is equivalent to .new followed by .save! (throws an error if saving fails). It's also just a wee bit shorter
  3. I think .build is mostly an alias for .new. It works one way in Rails 3 and another way in Rails < 3.x

The most important part, however, is that these methods can be called through an association (has_many, etc.) to automatically link the two models.


Although it is correct that create calls new and then save there is a big difference between the two alternatives in their return values.

Save returns either true or false depending on whether the object was saved successfully to the database or not. This can then be used for flow control as per the first example in the question above.

Create will return the model regardless of whether the object was saved or not. This has implications for the code above in that the top branch of the if statement will always be executed even if the object fails validations and is not saved.

If you use create with branching logic you are at risk of silent failures which is not the case if you use new + save.

create! doesn't suffer from the same issue as it raises and exception if the record is invalid.

The create alternative can be useful in controllers where respond_with is used for API (JSON/XML) responses. In this case the existence of errors on the object will cause the errors to be returned in the response with a status of unprocessable_entity, which is exactly what you want from an API.

I would always use the new + save option for html, especially if you are relying on the return value for flow control.


#create is shorter version of new and save. #create! is throwing exception if validation was not positive.


I'd second the above answers. Plus for create, one cannot pass false as an argument which you can do with save. Passing false as an argument will skip all rails validations