While working on rails applications, we face the requirement of, updating some attributes of an object without reloading page, quite often.
For example updating a value of a record in the grid by checking or unchecking a checkbox.
Often time we write functions that will take attribute name and the using Ajax we perform the required action. With this approach, we end up writing multiple js functions for collecting and updating attribute for different such updatable input fields. Such duplication of code at multiple places for the same behaviour is not good. Instead, a single technique can be used at all the places so that the code will be easy to maintain.
Let’s have a look at following simple approach.
STEP-1:
Add following function to application.js
$('.submittable').livequery('change', function() {
$(this).closest('form').submit();
});
STEP-2:
Add routes for updating user’s is_active attribute
resources :users do put :update_is_active, :on => :member end
STEP-3:
Add action to update the is_active attribute of a particular user.
class UsersController < ApplicationController def update_is_active @user = User.find(params[:id]) @user.update_attributes(params[:user]) end end
STEP-4:
Modify your table to have form in the td having checkbox.
When we check change the checkbox value the form will be submitted.
.flash-message
%table
%thead
%th Name
%th Active
%tbody
- @users.each do |user|
%tr
%td= user.name
%td
= form_for user, :url => update_is_active_user_url(user), :remote => true do |f|
= f.check_box :is_active, {:class => 'submittable', :id => "user_#{user.id}"}, true, false
STEP-5:
As per the submission of the form and on the update of the record the message can be shown.
In update_is_active.js.erb
$(‘
’).insertBefore(‘.flash-message’).fadeOut(3000); <% else %> $(‘
’).insertBefore(‘.flash-message’).fadeOut(3000); $(‘.submittable#user_’ + <%= @user.id %>).prop(‘checked’, false); <% end %>
On change after submission of the form you can do desired functionalities.
You can also add css effects or any animation for success/error message.
This technique is also good for Radio buttons and Select list.
Above is simple example for demo only but can be applied very effectively in complex contexts too.