Rails的更改与复选框和jQuery阿贾克斯布尔值 [英] Rails change boolean value with checkbox and jquery ajax
问题描述
我是新来的铁轨,并试图通过一个复选框来改变一个布尔值,并使用jquery ajax的:
<% - @ tasks.each做|任务| %GT;
< DIV CLASS =任务型包装>
<%= check_box_tag已完成,task.id,task.completed,:类=> 任务检查%>
<%= content_tag:跨度,task.task%GT;
<%= content_tag:跨度,task.deadline%GT;
< / DIV>
<%结束%GT;
和JavaScript的:
$(任务检查)。绑定('变',函数(){
如果(this.checked){
VAR BOOL = this.checked? 1:0;
$阿贾克斯({
网址:'/待办事项/切换,
输入:POST,
数据:{TASK_ID:'+ THIS.VALUE +',布尔:'+布尔+'}'
});
}
其他{
警报(否);
}
});
则控制器:
高清切换(TASK_ID,布尔)
@task = Todo.find_by_id(TASK_ID) 如果@task!=零?
@ task.update_attributes(:完成=>布尔)
其他
set_flash错误,请重试
结束
结束
终于路线:
资源:待办事项做
成员做
后切换
结束
结束
也试过集合,但给出了同样的错误。
块引用>当过我尝试它,我得到一个
404错误
上的操作。这是什么问题?
感谢
解决方案试试下面的(离开一切原样):
JavaScript的:
$(任务检查)。绑定('变',函数(){
如果(this.checked){
$阿贾克斯({
网址:'/todos/'+this.value+'/toggle',
输入:POST,
数据:{已完成:this.checked}
});
}
其他{
警报(否);
}
});控制器:
高清切换
@task = Todo.find(PARAMS [:ID]) 如果@ task.update_attributes(:完成=> PARAMS [:完成])
# ... 更新成功
其他
# ... 更新失败
结束
结束看看
捆绑EXEC耙路线
向您展示Rails生成的路径。在你的后'切换'
这是你得到像的路径/待办事项/一员的情况下:ID /切换
,因此更新URL中的阿贾克斯。在
控制器:ID
从路径结束PARAMS [:ID]
。从Ajax请求的数据在PARAMS
散也结束了,因此PARAMS [:完成]。
I am new to rails and trying to change the value of a boolean via a checkbox and using jquery ajax:
<%- @tasks.each do |task| %> <div class="task-wrapper"> <%= check_box_tag 'completed', task.id , task.completed, :class => "task-check" %> <%= content_tag :span, task.task %> <%= content_tag :span, task.deadline %> </div> <% end %>
and the 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"); } });
then the controller:
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
finally the routes:
resources :todos do member do post 'toggle' end end
also tried collection but gives the same error.
when ever i try it i get a
404 error
on the action.what is the problem?
thanks
解决方案Try the following (leaving everything else as is):
the javascript:
$(".task-check").bind('change', function(){ if (this.checked){ $.ajax({ url: '/todos/'+this.value+'/toggle', type: 'POST', data: {"completed": this.checked} }); } else { alert("no"); } });
the controller:
def toggle @task = Todo.find(params[:id]) if @task.update_attributes(:completed => params[:completed]) # ... update successful else # ... update failed end end
Take a look at
bundle exec rake routes
to show you the paths that rails generates. In the case of yourpost 'toggle'
which is a member you get a path like/todos/:id/toggle
, hence the updated url in the ajax.In the controller the
:id
from the path ends up inparams[:id]
. The data from the ajax request also ends up in theparams
hash, henceparams[:completed]
.这篇关于Rails的更改与复选框和jQuery阿贾克斯布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!