首先,我知道我想做的事情对于 Rails 来说并不典型。我愿意接受更好的替代方案的建议。我是 Rails 新手,所以欢迎提出建议:)
基本上,我有一个包含 5 个通知的通知栏。用户单击并看到通知后,我想将数据库中名为 saw 的列设置为 true。
这是我的 Jquery 函数:
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("div#count").html("<%= escape_javascript(render('shared/notification_count')) %>");
});
});
</script>
这是我仅在点击后尝试执行的代码(位于 _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) %>
但是,该代码似乎是在页面加载时自动执行的,而不是在单击后自动执行的。我的问题是什么?
最佳答案
首先,您不能简单地将 render
附加到按钮来更改数据库(无论是读取还是写入)。您必须使用类似
$.ajax({
url: "/path/to/your/method",
type: "GET",
dataType: "script"
});
在你的 Controller 中,你将处理你需要做的事情,然后用一个渲染你的js文件
respond_to do |format|
format.js {render 'shared/notification_count'}
end
这是因为当用户单击您的按钮时,代码将在客户端执行,但如果您从未向服务器发出请求,那么您将无法看到数据库的更新版本。我建议您阅读更多关于 this 的内容,这对我帮助很大。
关于jquery - rails : How to get Jquery to update a database column after a click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6643671/