和 JavaScript-6ren">
gpt4 book ai didi

ruby-on-rails - Rails 使用复选框和 jquery ajax 更改 boolean 值

转载 作者:行者123 更新时间:2023-12-03 22:05:56 24 4
gpt4 key购买 nike

我是 Rails 新手,尝试通过复选框并使用 jquery ajax 更改 boolean 值:

<%- @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 %>

和 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");
}
});

然后是 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

最后是路线:

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

also tried collection but gives the same error.

每当我尝试时,我都会收到 404 错误

问题是什么?

谢谢

最佳答案

从 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"
} %>

事实证明,将 remote: true 添加到输入会导致 jquery-ujs 以所有好的方式使其成为 ajax-y。 Thoughtbot 的 "A Tour of Rails jQuery UJS"简要介绍一下这一点(以及许多其他可用的好东西); "Unobtrusive scripting support for jQuery" page jQuery UJS wiki 中对此也做了彻底的工作。

关于ruby-on-rails - Rails 使用复选框和 jquery ajax 更改 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15572371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com