71 lines
1.4 KiB
Go
71 lines
1.4 KiB
Go
|
package models
|
||
|
|
||
|
import "net/http"
|
||
|
|
||
|
type askMan struct{}
|
||
|
|
||
|
// Questions is a singleton manager class for Question model access.
|
||
|
var Questions = askMan{}
|
||
|
|
||
|
// Question model.
|
||
|
type Question struct {
|
||
|
BaseModel
|
||
|
|
||
|
Name string
|
||
|
Question string
|
||
|
Answered bool
|
||
|
PostID int // FKey Post.id
|
||
|
|
||
|
// Relationships.
|
||
|
Post Post
|
||
|
}
|
||
|
|
||
|
// New creates a new Question model.
|
||
|
func (m askMan) New() Question {
|
||
|
return Question{}
|
||
|
}
|
||
|
|
||
|
// Load a comment by ID.
|
||
|
func (m askMan) Load(id int) (Question, error) {
|
||
|
var q Question
|
||
|
r := DB.Preload("Post").First(&q, id)
|
||
|
return q, r.Error
|
||
|
}
|
||
|
|
||
|
// Pending returns questions in need of answering.
|
||
|
func (m askMan) Pending() ([]Question, error) {
|
||
|
var q []Question
|
||
|
r := DB.Preload("Post").Where("answered=false").Find(&q)
|
||
|
return q, r.Error
|
||
|
}
|
||
|
|
||
|
// RecentlyAnswered returns questions that have blog posts attached.
|
||
|
func (m askMan) RecentlyAnswered(depth int) ([]Question, error) {
|
||
|
var qq []Question
|
||
|
r := DB.Preload("Post").
|
||
|
Where("answered=true AND post_id IS NOT NULL").
|
||
|
Order("created_at desc").
|
||
|
Limit(depth).
|
||
|
Find(&qq)
|
||
|
return qq, r.Error
|
||
|
}
|
||
|
|
||
|
// Save the question.
|
||
|
func (q Question) Save() error {
|
||
|
if DB.NewRecord(q) {
|
||
|
return DB.Create(&q).Error
|
||
|
}
|
||
|
return DB.Save(&q).Error
|
||
|
}
|
||
|
|
||
|
// Delete the question.
|
||
|
func (q Question) Delete() error {
|
||
|
return DB.Delete(&q).Error
|
||
|
}
|
||
|
|
||
|
// ParseForm sets the question's attributes from HTTP form.
|
||
|
func (q *Question) ParseForm(r *http.Request) {
|
||
|
q.Name = r.FormValue("name")
|
||
|
q.Question = r.FormValue("question")
|
||
|
}
|