package orm import ( "net/http" "git.andreafazzi.eu/andrea/oef/renderer" "github.com/jinzhu/gorm" ) type Answer struct { gorm.Model Text string Correct bool Question *Question QuestionID uint `schema:"question_id"` AllQuestions []*Question `gorm:"-"` Selected map[uint]string `gorm:"-"` } func (a *Answer) GetID() uint { return a.ID } func (a *Answer) String() string { return a.Text } func (a *Answer) Create(db *Database, args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) { if r.Method == "GET" { answer := new(Answer) if err := db._db.Find(&answer.AllQuestions).Error; err != nil { return nil, err } return answer, nil } else { answer := new(Answer) err := renderer.Decode(answer, r) if err != nil { return nil, err } answer, err = CreateAnswer(db, answer) if err != nil { return nil, err } return answer, nil } } func (a *Answer) Read(db *Database, args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) { var answer Answer id := args["id"] if err := db._db.Preload("Question").First(&answer, id).Error; err != nil { return nil, err } return &answer, nil } func (a *Answer) ReadAll(db *Database, args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) { var answers []*Answer if err := db._db.Preload("Question").Order("created_at").Find(&answers).Error; err != nil { return nil, err } return answers, nil } func (a *Answer) Update(db *Database, args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) { if r.Method == "GET" { result, err := a.Read(db, args, w, r) if err != nil { return nil, err } answer := result.(*Answer) if err := db._db.Find(&answer.AllQuestions).Error; err != nil { return nil, err } answer.Selected = make(map[uint]string) answer.Selected[answer.QuestionID] = "selected" return answer, nil } else { answer, err := a.Read(db, args, w, r) if err != nil { return nil, err } // FIXME: Should not be hard set. answer.(*Answer).Correct = false err = renderer.Decode(answer, r) if err != nil { return nil, err } _, err = SaveAnswer(db, answer) if err != nil { return nil, err } answer, err = a.Read(db, args, w, r) if err != nil { return nil, err } return answer.(*Answer), nil } } func (model *Answer) Delete(db *Database, args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) { answer, err := model.Read(db, args, w, r) if err != nil { return nil, err } if err := db._db.Unscoped().Delete(answer.(*Answer)).Error; err != nil { return nil, err } return answer.(*Answer), nil } func CreateAnswer(db *Database, answer *Answer) (*Answer, error) { if err := db._db.Create(answer).Error; err != nil { return nil, err } return answer, nil } func SaveAnswer(db *Database, answer interface{}) (interface{}, error) { if err := db._db.Omit("Answers").Save(answer).Error; err != nil { return nil, err } return answer, nil }