In the past, we couldn't use `polymorphic_path` in many places. For instance, `polymorphic_path(budget, investment)` would return `budget_budget_investment_path`, while in our routes we had defined `budget_investment_path`. With the `resolve` method, introduced in Rails 5.1, we can use symbols to define we want it to use `investment` instead of `budget_investment`. It also works with nested resources, so now we can write `polymorphic_path(investment)`. This makes the code for `resource_hierarchy_for` almost impossible to understand. I reached this result after having a look at the internals of the `resolve` method in order to get its results and then remove the symbols we include. Note using this method will not make admin routes compatible with `polymorphic_path`. Quoting from the Rails documentation: > This custom behavior only applies to simple polymorphic URLs where a > single model instance is passed and not more complicated forms, e.g: > [example showing admin routes won't work] Also note that now the `admin_polymorphic_path` method will not work for every model due to inconsistencies in our admin routes. For instance, we define `groups` and `budget_investments`; we should either use the `budget_` prefix in all places or remove it everywhere. Right now the code only works for items with the prefix; it isn't a big deal because we never call it with an item without the prefix. Finally, for unknown reasons some routing tests fail if we use `polymorphic_path`, so we need to redefine that method in those tests and force the `only_path: true` option.
46 lines
1.1 KiB
Ruby
46 lines
1.1 KiB
Ruby
class NotificationsController < ApplicationController
|
|
before_action :authenticate_user!
|
|
skip_authorization_check
|
|
|
|
respond_to :html, :js
|
|
|
|
def index
|
|
@notifications = current_user.notifications.unread
|
|
end
|
|
|
|
def show
|
|
@notification = current_user.notifications.find(params[:id])
|
|
@notification.mark_as_read
|
|
redirect_to linkable_resource_path(@notification)
|
|
end
|
|
|
|
def read
|
|
@notifications = current_user.notifications.read
|
|
end
|
|
|
|
def mark_all_as_read
|
|
current_user.notifications.unread.each(&:mark_as_read)
|
|
redirect_to notifications_path
|
|
end
|
|
|
|
def mark_as_read
|
|
@notification = current_user.notifications.find(params[:id])
|
|
@notification.mark_as_read
|
|
end
|
|
|
|
def mark_as_unread
|
|
@notification = current_user.notifications.find(params[:id])
|
|
@notification.mark_as_unread
|
|
end
|
|
|
|
private
|
|
|
|
def linkable_resource_path(notification)
|
|
if notification.linkable_resource.is_a?(AdminNotification)
|
|
notification.linkable_resource.link || notifications_path
|
|
else
|
|
polymorphic_path(notification.linkable_resource)
|
|
end
|
|
end
|
|
end
|