-
Notifications
You must be signed in to change notification settings - Fork 0
/
reply.rb
101 lines (88 loc) · 2.1 KB
/
reply.rb
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# require_relative 'questions_db'
class Reply < TableFinder
attr_accessor :question_id, :user_id, :parent_reply, :body
def initialize(options)
@table = 'replies'
@id = options["id"]
@question_id = options["question_id"]
@user_id = options["user_id"]
@parent_reply = options["parent_reply"]
@body = options["body"]
end
def self.find_by_id(id)
data = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
replies
WHERE
id = ?
SQL
raise "Not in table" if data.empty?
Reply.new(data[0])
end
def self.find_by_user_id(user_id)
data = QuestionsDatabase.instance.execute(<<-SQL, user_id)
SELECT
*
FROM
replies
WHERE
user_id = ?
SQL
raise "Not in table" if data.empty?
data.map { |datum| Reply.new(datum) }
end
def self.find_by_question_id(question_id)
data = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
*
FROM
replies
WHERE
question_id = ?
SQL
raise "Not in table" if data.empty?
data.map { |datum| Reply.new(datum) }
end
def update
QuestionsDatabase.instance.execute(<<-SQL, @user_id, @question_id, @parent_reply, @body, @id)
UPDATE
replies(user_id, question_id, parent_reply, body)
VALUES
(?, ?, ?, ?)
WHERE
id = ?
SQL
end
def create
QuestionsDatabase.instance.execute(<<-SQL, @user_id, @question_id, @parent_reply, @body)
INSERT INTO
replies(user_id, question_id, parent_reply, body)
VALUES
(?, ?, ?, ?)
SQL
@id = QuestionsDatabase.instance.last_insert_row_id
end
def author
User.find_by_id(@user_id)
end
def question
Question.find_by_id(@question_id)
end
def parent_reply
Reply.find_by_id(@parent_reply)
end
def child_replies
data = QuestionsDatabase.instance.execute(<<-SQL, @id)
SELECT
*
FROM
replies
WHERE
parent_reply = ?
SQL
raise "no children" if data.empty?
data.map { |datum| Reply.new(datum) }
end
end