Rails:如何让Jquery在单击后更新数据库列 [英] Rails: How to get Jquery to update a database column after a click

查看:35
本文介绍了Rails:如何让Jquery在单击后更新数据库列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道我想要做的事情并不是典型的Rails。我愿意接受更好的替代方案。我是rails的新手,欢迎提出建议:)

To start out, I know what I am trying to do is not typical to Rails. I open to suggestions to better alternatives. I am novice with rails so suggestions are welcome :)

基本上,我有一个有5个通知的通知栏。在用户单击并看到通知后,我想将数据库中的a列设置为true。

Basically, I have a notifications bar that has 5 notifications. After a user clicks and sees the notifications I want to set the a column in the database called seen to true.

这是我的Jquery函数:

Here is my Jquery function:

<script type="text/javascript">
            $(document).ready(function(){
              $("button").click(function(){
                    $("div#count").html("<%= escape_javascript(render('shared/notification_count')) %>");
              });
            });
</script>

这是我试图仅在点击后执行的代码(位于_notification_count.html中。 erb)

And here is the code I am trying to execute only after the click(located in _notification_count.html.erb)

<% notification_ids =   current_user.notifications.map(&:id).join(', ')%>
<% sql = "UPDATE notifications SET SEEN = true where id IN(#{notification_ids})" %>
<% User.connection.select_all(sql) %>

然而,看起来这个代码在页面加载时自动执行,而不是在点击之后执行。我的问题是什么?

However, it appears that this code is getting executed automatically when the page loads and not after the click. What is my problem?

推荐答案

首先,你不能简单地附上 render 按钮对数据库进行更改(无论是读取还是写入)。您必须使用类似

Firstly, you cannot simply attach a render to your button to make changes to your database (whether it's a read or a write). You must make an AJAX call back to your controller using something like

$.ajax({
    url: "/path/to/your/method",
    type: "GET",
    dataType: "script"
});

在您的控制器中,您将处理您需要做的事情,然后使用a渲染您的js文件

And in your controller you will handle what you need to do, and then render your js file with a

respond_to do |format|
    format.js {render 'shared/notification_count'}
end

this是因为当用户点击你的按钮时,代码将在客户端执行,但如果你从未向服务器发回请求,那么你将无法看到数据库的更新版本。我建议你在这个上阅读更多内容,这对我帮助很大。

This is because when a user clicks on your button, the code will be executed on the clients side, but if you never make a request back to the server, then you will not be able to see the updated version of your database. I suggest you reading more on this, that helped me a lot.

这篇关于Rails:如何让Jquery在单击后更新数据库列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆