-->

Change attribute using checkbox, AJAX, jQuery

2020-08-02 06:49发布

问题:

I wish to change the boolean attribute of my Task resource depending on wether checkbox is checked or not. I am stuck as I don't know what to do... I have everything before adding this AJAX checkbox working, whole CRUD, everything tested with rspec and capybara and bootstrapped. I have the following code...

views/tasks/show.html.erb

 27      <%= form_for [@project, @task], :remote => true do |f| %>
 28        <%= f.label :completed %>       
 29        <%= f.check_box :completed %>
 30      <% end %>

This :completed is the boolean attribute of the Task.

javascripts/tasks.js.coffee

  8 jQuery ->
  9   $('#task_completed').bind 'change', (event) =>
 10     $.post()

Dont know how to finish this $.post() thing and how to make code in the controller work... So far I only have this...

controllers/tasks_controller.rb

 1 class TasksController < ApplicationController
  2 
  3   before_filter :authenticate_user!
  4   before_filter :find_project_from_project_id
  5   before_filter :find_task, :only => [:show, :edit, :update]
  6 
  7   def show
  8     @title = @task.name
  9   end
 10 
 11   def new
 12     @title = 'New task'
 13     @task = @project.tasks.build
 14   end
 15 
 16   def create
 17     @task = @project.tasks.build(params[:task])
 18     if @task.save
 19       current_user.tasks.push(@task)
 20       redirect_to [@project, @task], :notice => 'Task created'
 21     else
 22       render 'new'
 23       flash.now[:alert] = 'Task not created'
 24     end
 25   end 
 26     
 27   def edit 
 28     @title = 'Edit task'
 29   end 
 30   
 31   def update
 32     if @task.update_attributes(params[:task])
 33       redirect_to [@project, @task], :notice => 'Task updated'
 34     else
 35       render 'edit'
 36       flash.now[:alert] = 'Task not updated'
 37     end
 38   end 
 39 
 40   private
 41   #controller doesn't respond to these methods as actions
 42   
 43   def find_project_from_project_id
 44     @project = current_user.projects.find(params[:project_id])
 45     rescue ActiveRecord::RecordNotFound
 46       redirect_to projects_path
 47       flash[:alert] = 'Project you were looking for could not be found'
 48   end
 49 
 50   def find_task
 51     @task = @project.tasks.find(params[:id])
 52     rescue ActiveRecord::RecordNotFound
 53       redirect_to project_path(@project)
 54       flash[:alert] = 'Task you were looking for could not be found'
 55   end
 56 
 57 end

Also, for those who want more... How to write tests for this thing? And should I write them at all for this?

EDIT: Upon research, I found people are doing it like this... Is this the way to go? Upon inspecting element I can see new requests are being made when i change the checkbox, but the boolean still remains false...

  8 jQuery ->
  9   $('#task_completed').bind 'change', (event) =>
 10     $('#task_completed').parents('form:first').submit()
 11     $('.task_headline').toggleClass('completed_task')

回答1:

This is not an elegant solution in so many ways, but it works :)

show.html.erb

<script>
window.monitorTaskCompletion(1,1)
</script>

tasks.coffee

window.monitorTaskCompletion = (project_id, task_id)  ->
    jQuery ->
      $('#task_completed').bind 'change', (event) =>
        $.ajax
          url: "/projects/#{project_id}/tasks/#{task_id}/complete"
          data: {completed: if $('#task_completed').is(':checked') then 1 else 0}
          type: "PUT"

tasks_controller.rb

def complete
  @completed = params[:completed].to_i > 0
  @task.complete(@completed)
  respond_to :js
end


回答2:

You are not providing the attributes to the $.post action.

Try to make something like this:

$('#task_completed').bind('change', function() {
    var url = $(this).closest('form').attr('action');
    var data = {};
    data.task = {};
    data.task.completed = $(this).is(':checked'); 
    $.post({
        url: url,
        data: data
    });
});

This will make the functionality you need, as you explained me over the IRC room. As checkboxes values are only sent if the checkbox is checked, we have to set a custom boolean value whether the checkbox is checked or not (achieved by the $(this).is(':checked') function).

Inspected the ajax request using Firebug or the Chrome/Opera/Safari inspector. You could add more functionalities in the $.post function, like a function to the the complete event. Take a look into the jQuery documentation about ajax and the $.post function:

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.post/



回答3:

Since this is an ajax action, you need to handle it differently in the controller than you normally would.

def update
  if @task.update_attributes(params[:task])
    @notice = 'Task updated'
  else
    @notice = 'Task not updated'
  end
end 

And in a update.js.erb view, something like:

$(#notice).html('<%= @notice %>')

In the jquery .post(), you also really should specify the url and include the data parameter, as suggested earlier.