Rails - 从js.erb文件更改数据库中的布尔值 [英] Rails - Changing boolean in database from js.erb file
问题描述
在我的情况下,在rails应用程序共享内容到Facebook后,我会得到一个响应对象与post id
In my scenario in rails application after sharing content to facebook i will get a response object with post id
post_id: "mypostidhere"
如果不成功,我将获得一个错误消息的响应对象。
If its not successful i will get response object with an error message.
因此,根据响应,我想更改我的数据库表中当前用户的最后一行的布尔列。在我的 .js.erb 文件中,我试图访问 current_user.model.last ,但它会引发以下错误。
So according to the response i want to change a boolean column of last row for the current user in my database table. And for this in my .js.erb file i tried to access current_user.model.last but it throws the following error.
undefined local variable or method `current_user' for
那么如何根据响应更改数据库中的布尔列?
So how can i change the boolean column in database according to the response?
UPDATED
Ajax代码
$.ajax({
type: "POST",
url: "/action"
});
控制器代码
def action
current_user.modal.last.toggle!(:boolean-column-name)
end
它成功更改了表列。但之后,我在浏览器CONSOLE中收到错误,如下所示
It changes the table column successfully. But after that i am receiving an error in browser CONSOLE as below
POST http://URL/action
500 (Internal Server Error)
我在ajax请求中做错了什么?提前感谢。
I am new to AJAX. What i am doing wrong in ajax request? Thanks in advance.
推荐答案
如果要更改数据库,您必须与Rails应用程序通信,这是通过 ajax
:
If you want to change the db, you're going to have to communicate with your Rails app, which is done with ajax
:
#app/assets/javascripts/application.js
... // your events will fire
$.ajax({
url: "/users/update",
method: "PUT",
data: { param: "value" }
success: function(data) {
// do something here
};
});
这将允许您执行以下操作:
This will allow you to do the following:
#config/routes.rb
resources :users do
put :update, on: :collection
end
#app/controllers/users_controller.rb
class UsersController < ApplicationController
def update
current_user.update(update_params)
end
private
def update_params
params.permit(:param)
end
end
这篇关于Rails - 从js.erb文件更改数据库中的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!