Ruby on rails 复选框不';不要使用Ajax
我有一个名为Ruby on rails 复选框不';不要使用Ajax,ruby-on-rails,ajax,Ruby On Rails,Ajax,我有一个名为:active的布尔字段,可以通过Ajax进行更改。我让它取消复选框,从而使布尔值为FALSE,或者在数据库中删除属性使其为空,但仍然有效 我的问题是它不能反过来工作。我可以选中该框使布尔值为TRUE,它似乎正在做一些事情,但实际上并没有在数据库中进行更改 Webbrick中的输出显示它已更新: Processing by CompaniesController#toggle as JS Parameters: {"Active"=>"228", "id"=>"228"
:active
的布尔字段,可以通过Ajax进行更改。我让它取消复选框,从而使布尔值为FALSE,或者在数据库中删除属性使其为空,但仍然有效
我的问题是它不能反过来工作。我可以选中该框使布尔值为TRUE,它似乎正在做一些事情,但实际上并没有在数据库中进行更改
Webbrick中的输出显示它已更新:
Processing by CompaniesController#toggle as JS
Parameters: {"Active"=>"228", "id"=>"228"}
SQL (0.5ms) UPDATE "companies" SET "active" = $1, "updated_at" = $2
WHERE "companies"."id" = $3 [["active", nil],
["updated_at", 2017-02-15 17:26:19 UTC], ["id", 228]]
(0.8ms) COMMIT
但是数据库没有更新。我看到上面写的是[[“active,nil]
,这是不正确的部分。所以从技术上讲,更新是有效的,但我很确定我的控制器是为什么在重新检查时发送nil
那么,如果我确实应该在控制器中发送布尔值TRUE
,我该如何发送呢
公司\u controller.rb
index.html.rb
编辑 我通过将控制器改为使用if语句来实现它。不确定这是否是最好的方法,但现在它确实在两个方向上都起作用了 公司\u controller.rb
您实际上不需要单独的路由。您只需向现有路由发送修补程序请求即可:
<% form_for(@company) do |f| %>
<%= f.check_box :active, class: "company-toggle-active" %>
<% end %>
如果您只是想修复现有代码,那么错误在于您正在使用
company.id
作为复选框的值,而不是布尔列。我最终看到,(active:params[:active])
给出的是id
,而不是布尔值。您的答案(如下)添加jQuery,但删除对路由的干扰。我也会尝试这种方法。如果您使用的是rails\u ujs,您已经将jQuery作为依赖项。
<%= check_box_tag 'Active', company.id, company.active,
data: {
remote: true,
url: url_for(action: :toggle, id: company.id),
method: "POST"
} %>
resources :companies do
resources :comments
member do
post 'toggle'
end
end
def toggle
@company = Company.find(params[:id])
if @company.active
@company.update_attributes(active: FALSE)
else
@company.update_attributes(active: TRUE)
end
end
<% form_for(@company) do |f| %>
<%= f.check_box :active, class: "company-toggle-active" %>
<% end %>
class CompaniesController < ApplicationController
# ...
def update
@company = Company.find(params[:id])
if @company.update(company_attributes)
respond_to do |f|
f.json { head :ok }
f.html { redirect_to @company }
end
else
respond_to do |f|
f.json { json: { errors: @company.errors }, status: 422 }
f.html { render :new }
end
end
end
private
def company_attributes
params.require(:company).permit(:foo, :bar, :active)
end
end
$(document).on('change', '.company-toggle-active', function(){
$.ajax({
url: this.form.action,
type: 'PATCH',
dataType: 'json',
data: {
company: {
active: $(this).is(':checked') ? 'true' : 'false'
}
}
}).done(function(data, textStatus, jqXHR){
// do something if request is successful
}).fail(function(data, textStatus, jqXHR){
// do something if request fails
});
});