Rails使用checkbox和jquery ajax更改布尔值

我是rails的新手,并尝试通过复选框和使用jquery ajax更改布尔值:

 
"task-check" %>

和javascript:

 $(".task-check").bind('change', function(){ if (this.checked){ var bool = this.checked ? 1 : 0; $.ajax({ url: '/todos/toggle', type: 'POST', data: '{"task_id":"'+ this.value +'", "bool":"'+ bool +'"}' }); } else { alert("no"); } }); 

那么控制器:

 def toggle(task_id, bool) @task = Todo.find_by_id(task_id) if @task != nil? @task.update_attributes(:completed => bool) else set_flash "Error, please try again" end end 

最后的路线:

 resources :todos do member do post 'toggle' end end 

也试过收集,但给出了同样的错误。

当我尝试它时,我在动作上得到404 error

问题是什么?

谢谢

尝试以下方法(保留其他所有内容):

javascript:

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

控制器:

 def toggle @task = Todo.find(params[:id]) if @task.update_attributes(:completed => params[:completed]) # ... update successful else # ... update failed end end 

看看bundle exec rake routes ,向您展示rails生成的路径。 如果您的post 'toggle'是一个成员,您会得到/todos/:id/toggle这样的路径,因此在ajax中更新了url。

在控制器中:id路径中的params[:id]params[:id] 。 来自ajax请求的数据也以params散列结束,因此params[:completed]

从Rails 4开始,有一种方法可以做到这一点,而无需任何额外的JS或CSS:

 <%= check_box_tag 'completed', task.id, task.completed, data: { remote: true, url: url_for(action: :toggle, id: task.id), method: "POST" } %> 

事实certificate,将remote: true添加到输入会导致jquery-ujs以所有好方式使其成为ajax-y。 Thoughtbot的“Rails之旅jQuery UJS”简要介绍了这个(以及其他许多好东西); jQuery UJS wiki中的“对jQuery的不显眼的脚本支持”页面也对此做了全面的工作。