Jeff Burghess Jeff Burghess - 6 months ago 15
Ruby Question

why is "if @user.save" used in this way?

I'm working through the Michael Hartl's rails book, and I'm curious how this works:

if @user.save

else

end


In if statements, the argument doesn't actually do anything much besides return true or false.

This method seems to save the model to the database and then return true or false. Is this common/am I right? Why do we do it this way?

Answer

Normally the if @user.save is checking if the object was successfully saved to the database using ActiveRecord. From there you could do something like set a flash message and redirect somewhere. In the else clause you could potentially inspect the @user.errors to see what went wrong and deal with it.

Example:

def create
  #Set user object attributes using strong parameters
  @user = User.new(user_params)

  #Attempt to save @user
  if @user.save
    flash[:notice] = 'User saved successfully'
    redirect_to somewhere_else_url
  else
    #Saving failed, we can inspect @user.errors for more information
    flash[:alert] = 'User was not saved.'

    #If using a form library @user.errors will be displayed graphically when rendering the :new action
    render :new
  end
end