in the application i'm working on, i need to install a notification system.
class Notification < ActiveRecord::Base
belongs_to :notifiable, polymorphic: true
end
class Request < ActiveRecord::Base
has_many :notifications, as: :notifiable
end
class Document < ActiveRecord::Base
has_many :notifications, as: :notifiable
end
after created, the notifications should redirect to differents view depending on the notification type, so it could be forthe same model and different redirections ( so the redirect_to notification.notifiable isn't a solution since i need many different redirections for that same model, not only the show). working with polymorphic_path or url, also dont give different redirections, only defined prefix helpers.
what i need more explicitly, for example there let's take two different types of notifications, the one where a request is submited, so clicking on it will redirect to the request itself, but when the request is done the user will be redirected to his dashboard.
i dont want to redirect to the notifications_controller and test on the model and then test again on the notification type, i hope that the polymorphism here could help. is there a way to call a method in the controller model (the model is detected from the polymorphic association )
and thanks
i ended up adding an attribute to the notification model, message_type : integer. Once the notification is clicked on, the redirection will always be the same : to a methode in the NotificationController (redirect_notification), now the notification known, also the depending model is too (from the polymorphic relation). in the NotificationController :
def redirect_notification
notification =Notification.find(params[:id]) // here i get the notification
notification.notifiable.get_notification_path(notification.message_type)
end
we take advantage of the poymorphic when using notification.notifiable. So, i define a method called get_notification_path(message_type) in each model who have a polymorphic association with notifications, as example :
class Document < ActiveRecord::Base
has_many :notifications, as: :notifiable
def get_notification_path(message_type)
if message_type == 0
"/documents"// this is just an example, here you can put any redirection you want, you can include url_helpers.
elsif message_type == 1
url_for user_path
end
end
end
This way, i get the redirection i need, using the polymorphic associations and without adding unneeded routes.