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



我知道那里有很多相关的问题,但我无法让我的问题工作。这是我所拥有的...

#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
...

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

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

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

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

有什么想法吗?

问题来自你的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");
}  
});

当您选中/取消选中该框时,将触发change事件,然后函数正在测试this.checked。当该框未选中时,它会返回 falsefalse,因此您不会进入条件内部,而是直接进入else,这会调用alert

因此,您可能希望删除该条件。

这就是浏览器的工作方式。它们不会发送未选中的复选框的值。

选中/取消选中需要根据参数的存在来确定。

谢谢安托万。那行得通...尽我所能学习JS。对于后代来说,这就是有效的...

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(){
$.ajax({
url: '/tasks/'+this.value+'/toggle',
type: 'POST',
data: {"checked_in": this.checked}
});
});
</script>

。此外,我在控制台中抛出了一个模板错误,所以这里是更新的控制器代码。

def toggle
@task = Task.find(params[:id])
@task.update_attributes(:checked_in => params[:checked_in])
render :nothing => true
end

最新更新