2014-01-29 63 views
0

通知belongs_to用户和用户have_many通知。清除用户通知

用户的显示(users_controller.rb)动作我通过检索用户的通知:

def show 
    ... 
    @notifications = current_user.notifications if current_user 
end 

通知是正常显示,但后来我想用户能够删除他/她的通知。我把这个在UsersHelper.rb:

def clearNotifications(notifs) 
    destroynotifs = notifs.destroy 
    end 

我的观点(用户/ show.html.erb),这没有任何意义是:

<div id="clearnotifications"> 
    <% clearNotifications(@notifications) %> 
    clear notifications 
</div> 

有三个问题,我关注:

  1. 这是一个很好的做法吗?
  2. 如何从视图上的文本调用此函数? (link_to?)
  3. 我不应该打电话给users.save或notifications.save?

在此先感谢您的任何提示/指导。如果您需要更多信息,请让我知道,我会马上添加。

回答

1

routes.rb get "notifications/clear" 首先创建一个控制器notifications_controller现在通知控制器创建明确的行动

def clear 
    current_user.notifications.delete_all 
    render nothing: true# or whatever you want to render 
end 

现在鉴于

<%= link_to "delete", notifications_clear_path, remote: true %> 
+0

谢谢。让我尝试一下。顺便说一句,我有一个通知控制器,因为我创建通知;在删除它们之前。 –

1

应该有一个控制器动作(users_controller#delete_notificationsnotification_controller#delete_all或其他),删除通知。

例如,您可以从JavaScript调用该操作。

这里的关键是:这个虚构的html-ruby桥梁不存在。

<div id="clearnotifications"> 
    <% clearNotifications(@notifications) %> 
    clear notifications 
</div> 

您不能以这种方式调用服务器端代码。要删除通知,您必须发送一个请求(通过点击链接重新加载页面或使用javascript发送异步请求)。例如,请参阅关于jQuery.ajax的文档。

+0

关于看法,这就是为什么我提到:“我的观点(用户/ show.html.erb)这是没有意义的“ –