-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrelationships_controller.rb
More file actions
85 lines (71 loc) · 2.33 KB
/
relationships_controller.rb
File metadata and controls
85 lines (71 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# typed: strict
# frozen_string_literal: true
class RelationshipsController < ApplicationController
extend T::Sig
before_action :authenticate_or_redirect_user
class CreateParams < T::Struct
const :section_id, Integer
const :subscribe, T::Boolean
end
sig { void }
def create
typed_params = TypedParams.extract!(CreateParams, params)
section = Section.find(typed_params.section_id)
user = T.must(current_user)
if typed_params.subscribe
user.subscribe_to_section(section)
render(json: { msg: "Subscribed" })
else
user.follow_section(section)
render(json: { msg: "Followed" })
end
end
class DestroyParams < T::Struct
const :section_id, Integer
const :subscription_only, T::Boolean
end
sig { void }
def destroy
typed_params = TypedParams.extract!(DestroyParams, params)
user = T.must(current_user)
relationship = user.relationships.find_by!(section_id: typed_params.section_id)
section = T.must(relationship.section)
if typed_params.subscription_only
user.unsubscribe_to_section(section)
render(json: { msg: "Unsubscribed" })
else
begin
user.unfollow(section)
render(json: { msg: "Unfollowed" })
rescue ActiveRecord::RecordNotDestroyed
render(json: { msg: "You cannot unfollow a class you've reviewed! Did you mean to unsubscribe?" }, status: :bad_request)
end
end
end
class UnsubscribeParams < T::Struct
const :id, Integer
end
sig { void }
def unsubscribe
typed_params = TypedParams.extract!(UnsubscribeParams, params)
user = T.must(current_user)
section = Section.find(typed_params.id)
course = section.course
successfully_unsubscribed = user.unsubscribe_to_section(section)
if successfully_unsubscribed
flash[:success] = "Unsubscribed to alerts for #{course.short_title}"
else
flash[:error] = "You aren't subscribed to notifications for #{course.short_title}!"
end
redirect_to(my_courses_url)
end
private
# Devise has a method that does this, authenticate_user!, but it returns 401
# instead of a redirect on AJAX requests.
sig { void }
def authenticate_or_redirect_user
return if user_signed_in?
flash[:error] = "You must be logged in to follow a class!"
redirect_to(new_user_session_path, turbolinks: false)
end
end