gpt4 book ai didi

ruby-on-rails - 在 Rails 中,我应该如何使用 ajax 更新数据库中的值?

转载 作者:行者123 更新时间:2023-12-03 16:20:52 24 4
gpt4 key购买 nike

勾选复选框后,我只想更新数据库中的“Needed”值。脚本如下所示

 $('td div').find('input[type=checkbox]').click(function(){
$.ajax({
type: "PUT",
dataType: "script",
url: '/ecs/2',
contentType: 'application/json',
data: JSON.stringify({ ecs:{needed:'N'}, _method:'put' })
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});
});

});并且 Controller 的代码是标准的。

# PATCH/PUT /ecs/1
# PATCH/PUT /ecs/1.json
def update
respond_to do |format|
if @ec.update(ec_params)
format.html { redirect_to @ec, notice: 'Ec was successfully updated.' }
format.json { head :no_content }
format.js
else
format.html { render action: 'edit' }
format.json { render json: @ec.errors, status: :unprocessable_entity }
format.js
end
end
end

EC 是模块的名称,需要的是列的名称。我只想用 id=2 更新 ec 所需的新值。但是现在,我总是遇到BAD REQUEST。我不确定问题出在哪里。

最佳答案

对于你的复选框(让它不显眼,这只是一个简单的例子):

... onclick="$.post('/url', {omg_it_is_checked: $(this).attr('checked')})"

routes.rb 中:

post '/url' => 'my_controller#my_action'

在 Controller 中:

def my_action
#....
@var = some.actions.here.with(params[:omg_it_is_checked]) #or update what you need
respond_to do |format|
format.js{render layout: false}
end
end

你必须有一个合适的 View my_action.js.erb 像这样:

$('#my_uniq_dom_id').html('<%= j render partial: 'new_piece_of_html' %>') #you can render nothing or flash something

最后我们需要的是 _new_piece_of_html.html.erb:

<div id="new_ajaxed_content"><%= @var %></div> <!-- or you can render checked checkbox, even with animation, or error message if in some reason it was not saved -->

瞧! div#my_uniq_dom_id 在 Controller 操作后更新为 div#new_ajaxed_content


完全不同的方法 - 使用 this gem 。这是简单需求的简单解决方案

干杯!

关于ruby-on-rails - 在 Rails 中,我应该如何使用 ajax 更新数据库中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17854732/

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