diff --git a/app/controllers/subscriptions_controller.rb b/app/controllers/subscriptions_controller.rb new file mode 100644 index 00000000..388e72a6 --- /dev/null +++ b/app/controllers/subscriptions_controller.rb @@ -0,0 +1,39 @@ +class SubscriptionsController < ApplicationController + include TurboStreamable + + before_action :authenticate_user! + + turbo_stream_actions :create, :destroy + + def create + answer = Answer.find(params[:answer]) + result = Subscription.subscribe(current_user, answer) + + respond_to do |format| + format.turbo_stream do + render turbo_stream: [ + turbo_stream.replace("subscription-#{answer.id}", partial: "subscriptions/destroy", locals: { answer: }), + render_toast(t(result.present? ? ".success" : ".error"), result.present?) + ] + end + + format.html { redirect_to answer_path(username: answer.user.screen_name, id: answer.id) } + end + end + + def destroy + answer = Answer.find(params[:answer]) + result = Subscription.unsubscribe(current_user, answer) + + respond_to do |format| + format.turbo_stream do + render turbo_stream: [ + turbo_stream.replace("subscription-#{answer.id}", partial: "subscriptions/create", locals: { answer: }), + render_toast(t(result.present? ? ".success" : ".error"), result.present?) + ] + end + + format.html { redirect_to answer_path(username: answer.user.screen_name, id: answer.id) } + end + end +end diff --git a/app/views/subscriptions/_create.html.haml b/app/views/subscriptions/_create.html.haml new file mode 100644 index 00000000..d35861aa --- /dev/null +++ b/app/views/subscriptions/_create.html.haml @@ -0,0 +1,3 @@ += button_to subscriptions_path(answer: answer.id), class: "dropdown-item", id: "subscription-#{answer.id}" do + %i.fa.fa-fw.fa-bell + = t("voc.subscribe") diff --git a/app/views/subscriptions/_destroy.html.haml b/app/views/subscriptions/_destroy.html.haml new file mode 100644 index 00000000..89f57ede --- /dev/null +++ b/app/views/subscriptions/_destroy.html.haml @@ -0,0 +1,3 @@ += button_to subscriptions_path(answer: answer.id), method: :delete, class: "dropdown-item", id: "subscription-#{answer.id}" do + %i.fa.fa-fw.fa-bell-slash + = t("voc.unsubscribe") diff --git a/config/routes.rb b/config/routes.rb index e5fcf899..5004d57c 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -148,6 +148,8 @@ Rails.application.routes.draw do post "/inbox/create", to: "inbox#create", as: :inbox_create get "/inbox", to: "inbox#show", as: :inbox + resource :subscriptions, controller: :subscriptions, only: %i[create destroy] + get "/user/:username", to: "user#show" get "/@:username", to: "user#show", as: :user get "/@:username/a/:id", to: "answer#show", as: :answer