当通知按钮被点击时,它会向 Controller 发送一个获取请求, Controller 应该将 Activity.viewed 从 false 更新为 true。这样我的 js 就知道不要将它重新填充到通知计数中。所以:
我有一个 ajax GET 请求
// click EVENT TRIGGERS
$('#bell-notices').click(function(){
var $bell = $(this);
$bell.find('.notifications-count').hide('0');
$bell.parent().find('.dropdown-toggle').dropdown();
$.get('/activities/mark_activity_viewed', function( data ) {
});
});
被发送到 rails Controller
def mark_as_viewed
@mark = Activity.find_by(params[:id])
@mark.viewed = true
@mark.save!
end
一切似乎都已就绪,但我无法更新数据库。
Activity.last 的控制台
<Activity id: 190, user_id: 68, action: "created", targetable_id: 157, targetable_type: "Status", created_at: "2015-03-04 21:17:57", updated_at: "2015-03-04 21:17:57", commentable_id: nil, reference_id: nil, viewed: false>
在这种情况下,user_id 是创建事件的用户,而不是接收事件的用户。
最佳答案
不要使用 $.get() 进行更新数据的调用。改为通过 PUT 发送请求。由于您正在更新所有用户的事件,因此您不需要执行 Activity.find 查找。我假设您的用户模型定义了一个 'has_many :activities' 关联。你的 JS 看起来像这样(我正在使用 coffeescript):
$('#bell-notices').click ->
$bell = $(this)
$bell.find('.notifications-count').hide '0'
$bell.parent().find('.dropdown-toggle').dropdown()
$.ajax
url: '/activities/mark_activity_viewed'
type: 'put'
(作为 JS):
$('#bell-notices').click(function() {
var $bell;
$bell = $(this);
$bell.find('.notifications-count').hide('0');
$bell.parent().find('.dropdown-toggle').dropdown();
$.ajax({
url: '/activities/mark_activity_viewed',
type: 'put'
});
});
在您的 activities_controller 中,您将拥有:
def mark_activity_viewed
current_user.activities.update_all(viewed: true)
[any respond_to stuff you care to do...]
end
你需要在 routes.rb 中有一个匹配 'put' 的路由
put 'activities/mark_activity_viewed' => 'activities#mark_activity_viewed'
请注意,上面的“update_all”将跳过 Activity 的验证,但由于您在这里所做的只是更改 bool 值,所以这应该不是问题。如果您希望对每个事件执行验证,循环遍历它们并执行典型的更新并保存!
将其放入哪个 Controller 完全取决于您。我会把它放在 users_controller 中,因为它是一个更以用户为中心的操作,但将它放在事件 Controller 中也没有错。
关于javascript - 在 rails 中使用 ajax 请求更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28864079/