boo
boo

Reputation: 83

Implementing AJAX call on checkbox in Rails to update db

Rails newbie here.

I am trying to make a checkbox called "Active" that will act as a form when the checkbox is checked/unchecked and use AJAX to automatically update the database with the changed attribute (without a submit button). I am using the instructions here: http://trevorturk.com/2010/08/24/easy-ajax-forms-with-rails-3-and-jquery/ but can't seem to make it work correctly.

In my view:

<%= form_for @post, :remote => true do |f| %>
<%= f.label :active %>
<%= f.check_box :active, :class => 'submittable' %>
<% end %>

In my posts_controller.rb

def update
if @post.update(post_params)
  flash[:notice] = "Your post was edited."
  redirect_to post_path(@post)
else
  render :edit
end
end

Then I made a file called 'archive.js.erb' in my views/posts folder with this code:

$('.submittable').live('change', function() {
  $(this).parents('form:first').submit();
});

Upvotes: 1

Views: 2136

Answers (1)

paulorcdiniz
paulorcdiniz

Reputation: 164

I've tried your code, and the problem seems to be on the live method on javascript. It works if i change to the click function:

$(document).ready(function(){

    $('.submittable').click(function() {
        $(this).parents('form:first').submit();
    });

}); 

Edit: Forgot to mention that this javascript was included in app/assets/javascripts directory. This is because the javascript must be loaded on document.ready for the jQuery ajax to have the effect that you want.

The arquive.js.erb file must exist in the case that you have an arquive action on your controller, and the javascript code that is in it will be executed later. This is not your case.

Upvotes: 2

Related Questions