简体   繁体   English

Rails-从js.erb文件更改数据库中的布尔值

[英]Rails - Changing boolean in database from js.erb file

In my scenario in rails application after sharing content to facebook i will get a response object with post id 在我的场景在Rails应用程序中,在将内容共享给Facebook之后,我将获得带有帖子ID的响应对象

post_id: "mypostidhere"

If its not successful i will get response object with an error message. 如果未成功,我将获得带有错误消息的响应对象。

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. 为此,在我的.js.erb文件中,我尝试访问current_user.model.last,但它引发以下错误。

undefined local variable or method `current_user' for 

So how can i change the boolean column in database according to the response? 那么如何根据响应更改数据库中的布尔值列?

UPDATED 更新

Ajax code Ajax代码

 $.ajax({
        type: "POST",
        url: "/action"
    });

Controller code 控制器代码

def action
  current_user.modal.last.toggle!(:boolean-column-name)
end

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)

I am new to AJAX. 我是AJAX的新手。 What i am doing wrong in ajax request? 我在ajax请求中做错了什么? Thanks in advance. 提前致谢。

current_user is not a local variable to your JS function/file, it is a helper provided and available in your rails application. current_user不是您的JS函数/文件的本地变量,它是Rails应用程序中提供并可用的帮助程序。

So, what I will like to ask is: 因此,我想问的是:

How are you using current_user in the JS file? 您如何在JS文件中使用current_user

What you can do is to make an ajax call to a controller method, and then access current_user directly from the controller. 您可以做的是对控制器方法进行ajax调用,然后直接从控制器访问current_user

If you want to change the db, you're going to have to communicate with your Rails app, which is done with ajax : 如果要更改数据库,则必须与Rails应用程序通信,这是通过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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM