2014-01-29 98 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)這是沒有意義的「 –