Rails UJS for Forms

 Dec 2015

JS frameworks are fun, but for most apps a sprinkling of JavaScript and Rails RJS gets a lot done, it’s simple to use and easy to maintain.

Often, a feature requires a form to be added to the list page allowing a user to add elements. It’s nice if this works with Ajax, without a page reload as the user adds the elements.

To get started, add a remote attribute and id to the link to the new action.

<%= link_to "Add Friend to This List",
            remote: true, id: 'new_friend' %>

In your form partial, tell the form to use ajax using the remote attribute:

<%= simple_form_for( [@list, @friend], remote: true) do |f| %>

Tell the create action to render the JS view instead of the usual html view.

if @friend.save
        format.html { redirect_to @friend.list,
                  notice: 'Friend was successfully created.' }


Create a create.js view and the JS you want when the friend is created. Remember to use the ‘j’ helper to escape the content.

$('#friends').append('<%= j render @friend %>');

For a bonus, it’s nice to allow the user to close the form when they are done.

add the following to the application.js:

  $( document ).on('click', '.done', function(e) {

and then add a link to the form to close it.

  <a href="#" class="done"


Web Development

Got a web project you need doing well? We can help with that!

Find out more