0
votes

I have two domain classes as following

class Quiz {
    String name
    String description
    int duration
    User user
    int points
    static hasMany = [questions:Question]
}

and

class Question {
    String question
    String questionType
    int points  
    String option_1
    String option_2
    String option_3
    String option_4
    boolean isOption_1_Correct
    boolean isOption_2_Correct
    boolean isOption_3_Correct
    boolean isOption_4_Correct
    User user
    static belongsTo = [user:User]
}

static hasMany = [questions:Question] in Quiz class has made my life a lot easier. I also understand it will be able to use convenience methods like addTo and removeFrom. Only query I have is that I want users to be able to define display order for the questions. Is there an easier way to do this or do I have to create a mapping class like following?

class QuestionInQuiz {
    Quiz quiz
    Question question
    int displayOder
    static constraints = {
        question unique:['quiz']
    }
}

It will be great if i can somehow avoid using this mapping class and keep my code simpler!

2

2 Answers

0
votes

If you add

List questions

to your Quiz class (in addition to the hasMany) then GORM will use a List for the association rather than the default unordered Set. The Grails docs explain the details.

0
votes

You can add a position property to Question class. You should add a mapping static closure to Quiz class:

static mapping = {
    questions sort:'position'
} 

Then you should to link the Question with the Quiz -> belongsTo = [user: User, quiz: Quiz]

I believe that you can to refine your model creating a Option class and an enumeration QuestionType What happen if tomorrow you have a question with 5 or 6 options? You want to rewrite, retest, recompile and redeploy your code?

Or your can to implement the Comparable interface in Question and to create a SortedSet of questions

class Quiz {
    SortedSet questions
    String name
    String description
    int duration
    User user
    int points
    static hasMany = [questions:Question]
}

class Question implements Comparable<Question> {
    String question
    String questionType
    int points  
    int position
    String option_1
    String option_2
    String option_3
    String option_4
    boolean isOption_1_Correct
    boolean isOption_2_Correct
    boolean isOption_3_Correct
    boolean isOption_4_Correct
    User user
    static belongsTo = [user:User]

    int CompareTo(obj){
        position <=> obj.position
    }
}