user2911232
user2911232

Reputation:

Clear user notifications

Notifications belong_to users and users have_many notifications.

On user's show (users_controller.rb) action I retrieve the user's notifications by:

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

Notifications are shown properly but then I want to the user to be able to delete his/her notifications. I placed this in the UsersHelper.rb:

  def clearNotifications(notifs)
    destroynotifs = notifs.destroy
  end

My view (users/show.html.erb) which doesn't make sense is:

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

There are three issues I am concerned about:

  1. Is this a good practise?
  2. How do I call this function from the text on the view? (link_to?)
  3. Shouldn't i call users.save or notifications.save?

Thanks in advance for any tips/guidance. If you need any more info let me know and I will add it right away.

Upvotes: 0

Views: 307

Answers (2)

Nitin Jain
Nitin Jain

Reputation: 3083

first create a controller notifications_controller now in routes.rb get "notifications/clear" create clear action in notifications controller

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

now in view

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

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230441

There should be a controller action (users_controller#delete_notifications or notification_controller#delete_all or something else) that does deletion of notifications.

You can then, for example, call that action from javascript.

The key point here is: this imaginary html-ruby bridge does not exist.

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

You can't call server-side code in this manner. To delete notifications, you have to send a request (by clicking a link to reload page or sending async request with javascript).

See docs on jQuery.ajax, for example.

Upvotes: 1

Related Questions