WB
Home About Work Notes

Rails UJS for Forms

  16th December 2015
  1 minute
  Rails

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",
            new_list_friend_path(@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.' }
        format.js

...        

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 %>');
$('#q').val('');

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:

$(function(){
  $( document ).on('click', '.done', function(e) {
    $($(event.target).data("show")).show();
    $($(event.target).data("remove")).remove();
  });
});

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

  <a href="#" class="done"
    data-remove="#new_friend"
    data-show="#new_friend_link">Cancel</a>

References

  • http://railscasts.com/episodes/136-jquery-ajax-revised?view=asciicast
  • http://guides.rubyonrails.org/v4.2/working_with_javascript_in_rails.html
  • https://robots.thoughtbot.com/a-tour-of-rails-jquery-ujs

Lets make something together!

Get in touch at [email protected]


Copyright 2024 © All rights Reserved.
Crafted Web Development. Built With