1

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();
});

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hello, thank you for the response. Do you mean that I have to put this code into the apps/assets/javascripts/application.js file? Even if I do that, it does that work for me still
Did you add the js inside the ready function? Maybe try to create a new js file inside the javascripts directory with the code.
Yes, I tried it inside the ready function and also with a new js file and still this did not solve the issue for me. Do I need to call on the new js file anywhere?
Oh sorry! I am checking now and it seems to work sometimes only, but it does work partially. I can check to see what kind of bugs I can solve. Thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.