I have a User who can have 0 or 1 Profiles. In my Controller, I want to save the profile if some of the values are given, as follows:
# PUT /users/1
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
if params[:profile][:available] == 1 #available is a checkbox that stores a simple flag in the database.
@user.create_profile(params[:profile])
end
else
#some warnings and errors
end
end
The part I am wondering about is create_profile, the magic create_somerelationname. How does that compare to the magic build_somerelationname? And when should I use which?
The difference between
buildandcreateis that create also saves the created object as build only returns the newly created object (without it being saved yet).The documentation is somewhat hidden away here.
So, depending whether you are happy with the returned object or not, you need
create(since you will not change it anymore) respectivelybuildas you want to update it before saving again (which will save you a save operation)