Rails、Ajax 和布尔值;无法取消复选框

Mar*_*ear 0 javascript ajax ruby-on-rails

我知道有一堆相关的问题,但我无法让我的工作。这是我所拥有的...

#app/views/tasks/index.html.erb
<%- @tasks.each do |task| %>
  <div class="task-wrapper">
    <%= check_box_tag 'checked_in', task.id , task.checked_in, :class => "task-check" %>
    <%= content_tag :span, task.name %>
  </div>
<% end %>
<%= link_to 'New Task', new_task_path %>

  <script>
$(".task-check").bind('change', function(){
  if (this.checked){
    $.ajax({
      url: '/tasks/'+this.value+'/toggle',
      type: 'POST',
      data: {"checked_in": this.checked}
    });
  }
  else {
     alert("no");
  }
});
  </script>

#app/controllers/tasks_controller.rb
...
def toggle
  @task = Task.find(params[:id])

  if @task.update_attributes(:checked_in => params[:checked_in])
    # do I need something here?
  else
    # do I need something here?
  end
end
...
Run Code Online (Sandbox Code Playgroud)

我的任务模型有一个布尔值的“checked_in”属性。

我从这个问题中得到了这个代码......

Rails 使用复选框和 jquery ajax 更改布尔值

......并且不太了解正在发生的一切。当我创建一个新任务时,我可以成功选中该框以将我的布尔值设置为 true。但是,当我取消选中该框时,我会弹出 js 弹出窗口,上面写着“否”,但在数据库中没有设置任何内容,也没有任何内容发送回服务器。

有任何想法吗?

Ant*_*ine 5

问题来自您的 js 代码

$(".task-check").bind('change', function(){
  if (this.checked){
    $.ajax({
      url: '/tasks/'+this.value+'/toggle',
      type: 'POST',
      data: {"checked_in": this.checked}
    });
  } 
  else {
    alert("no");
  }  
});
Run Code Online (Sandbox Code Playgroud)

当您选中/取消选中该框时,将change触发事件,然后函数正在测试this.checkedfalse取消选中该框时,它返回 false ,因此您无需进入条件,而是直接进入else调用alert.

所以你可能想删除条件。