Using AJAX with Rails CRUD

This one has caused me DAYS of Googling.

Tags: AJAX, Ruby on Rails, Javascript

Back to Blogs

So the purpose of AJAX is to create (or edit, or delete...you get it) a new thing and have it save to the database, and get added to an area of the page....all without reloading the page itself. In this example, I'm trying to create a new notecard and have it automatically show up below the form without reloading the page.

There are several components of an AJAX call with Ruby on Rails, so let's go through step by step.

First, you have to add remote: true on your form for whatever is getting CRUD-ded:

   <%= simple_form_for(topic, remote: true) do |f| %>

Then you have to make sure that the controller can handle javascript as well as html:

 def create
    @notecard = Notecard.new(notecard_params)

    respond_to do |format|
      if @notecard.save
        format.js do
          @notecards = Notecard.where(user_id: @notecard.user_id, source_id: @notecard.source_id)
        end
      else
        format.html { render :new }
        format.json { render json: @notecard.errors, status: :unprocessable_entity }
      end
    end
  end

If you need to do format.js do you can pass in variables in a do block.

Next you have to make sure you have a javascript file with instructions for what to do inside your view folder. (So here it'll be views/notecards/create.js.erb.):

$('#notecardRow').html('<%= j render partial: "notecards/notecards", locals: { notecards: @notecards } %>');
$('#notecardForm').html('<%= j render partial: "notecards/form", locals: { notecard: Notecard.new, source: @source } %>');

Note, sometimes these variables have to be passed in through a controller. It's a bit of a trial and error situation, but that should get you most of the way!


Back to Blogs