ruby-on-railsjsonrubyajaxrespond-to

Getting status: code on ajax response in a .js.erb file on Rails


I've just started to play with Rails applications and I'm trying to use Ajax on a form, but I don't know how to catch the status code inside a js.erb file. I'm following this tutorial: http://guides.rubyonrails.org/working_with_javascript_in_rails.html

On my Users controller I have a code for my update method:

respond_to do |format|
        if @user.save
            format.html { redirect_to @user, notice: 'User was successfully created.' }
            format.js {}
            format.json { render json: @user, status: :created, location: @user}
        else 
            format.html { render action: 'edit' }
            format.js {}
            format.json { render json: @user, status: :unprocessable_entity }
            logger.debug @user.response_errors
        end         
    end

I've created a update.js.erb file inside my views/users/ folder and is very easy to debug the @user var, but I don't know how to get the status code setted on my method.

Sorry if it's a stupid question, but I'm new with rails and I'm trying to follow all the frameworks concepts to the letter and I don't know the best pratices to create responses to Ajax requests.

What I'm trying to achieve is something like this:

#on my update.js.erb
if( status == 'created' ) {
   alert( 'Ok, created' )
} else {
   alert( 'Something wrong happened' )
}

I appreciate any help.


Solution

  • Option 1: Check Validity Inside update.js.erb

    This is the option that I recommend in most cases.

    update.js.erb is an ERB template whose result is a JavaScript code to evaluate on the client. In this case, you can make it look like:

    <% if @user.valid? %>
      alert('Ok, created');
    <% else %>
      alert('Something wrong happened');
    <% end %>
    

    The decision which alert to displays happens server-side. The client receives either:

    alert('Ok, create');
    

    or

    alert('Something wrong happened');
    

    depending on the status of @user.

    Option 2: Two separate js.erb files

    You can split your update.js.erb into two files. update.js.erb should contain the happy path code:

    alert('Ok, create');
    

    update-error.js.erb should contain some error handling:

    alert('Something wrong happened');
    

    Then you decide which one to display in your controller:

    respond_to do |format|
      if @user.save
        # ...
        format.js {}
        # ...
      else 
        # ...
        format.js { render 'update-error' }
        # ...
      end         
    end