Jeff Burghess Jeff Burghess - 1 year ago 49
Ruby Question

why is "if" used in this way?

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




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 Source

Normally the if 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.


def create
  #Set user object attributes using strong parameters
  @user =

  #Attempt to save @user
    flash[:notice] = 'User saved successfully'
    redirect_to somewhere_else_url
    #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