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

后端 未结 4 2007
遇见更好的自我
遇见更好的自我 2020-12-07 06:47

So I\'ve been seeing people using .build, .create, and .create! within their controllers more and more lately. What\'s the difference

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 07:28

    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.

提交回复
热议问题