-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquestion.rb
102 lines (79 loc) · 1.8 KB
/
question.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
102
class Question
def self.all
results = QuestionDatabase.instance.execute('SELECT * FROM questions')
results.map { |result| Question.new(result) }
end
def self.find_by_id(id)
results = QuestionDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
questions
WHERE
id = ?
SQL
Question.new(results.first)
end
def self.find_by_author_id(author_id)
results = QuestionDatabase.instance.execute(<<-SQL, author_id)
SELECT
*
FROM
questions
WHERE
user_id = ?
SQL
results.map {|result| Question.new(result)}
end
def self.most_followed(n)
QuestionFollow::most_followed_questions(n)
end
def self.most_liked(n)
QuestionLike::most_liked_questions(n)
end
attr_accessor :title, :body
attr_reader :id, :user_id
def initialize(options = {})
@id = options['id']
@title = options['title']
@body = options['body']
@user_id = options['user_id']
end
def save
if id.nil?
QuestionDatabase.instance.execute(<<-SQL, title, body, user_id)
INSERT INTO
questions(title, body, user_id)
VALUES
(?, ?, ?)
SQL
@id = QuestionDatabase.instance.last_insert_row_id
else
QuestionDatabase.instance.execute(<<-SQL, title, body, user_id, self.id)
UPDATE
questions
SET
title = ?,
body = ?,
user_id = ?
WHERE
id = ?
SQL
end
end
def author
User::find_by_id(self.user_id)
end
def replies
Reply::find_by_question_id(self.id)
end
def followers
QuestionFollow::followers_for_question_id(self.id)
end
def likers
QuestionLike::likers_for_question_id(self.id)
end
def num_likes
QuestionLike::num_likes_for_question_id(self.id)
end
end