开发者

save Elements in Map/Array/Collection ...... Grails

I'm new to grails 1.3.7 and I have a problem.

I want to store different elements/paramters in one list/array/map/whatever.. the data to be stored looks like this:

id : answera, answerb, answerc, answerd, answere, answerf, answerg, answerh

id is a number

answers are booleans

so Ive got a lot of ids (well, maybe 20) and for each one 8 answers-booleans. How do I store them the best, so that I can access them very easy again?

Thank you :-)

[EDIT] Thanks a lot for those answers, I will try it out now! :-)

I have now a map containing an id (int) and an object representing my answers (its a pojo which conta开发者_运维技巧ins booleans answera, answerb, etc...)

Now I give this map to a gsp. How do I know get the data out of it? Thanks for help! :-)


A Map would be the best approach, however it really has nothing to do with grails. Do you need to persist these to a Domain Class/Database?

What a map would look like...

def map = [:]
map.put(id1, [new Answer(accepted:true), new Answer(accepted:false)]; 
map.put(id2, [new Answer(accepted:false), new Answer(accepted:false)]; 

I don't think this would give you an easy domain class to work with. Sounds like you would want a grails domain class to encapsulate the answers. Something like...

class Question{

    static hasMany = [answers:Answer]
    Integer id
    Boolean answered

    def hasBeenAnswered(){
        answers.each(){ answer->
            if (answer.accepted){
                answered = true;
                return true;
            }
        }
        return false;
    }

    def acceptAnwser(Answer answer){

        answer.accepted = true;
        this.answered = true;

    }


}

class Answer{

    static belongsTo = [question:Question]

    Integer id
    Boolean accepted
    String text
}

And then your code would be easier to use...

def allQuestion = Question.list();
def allUnansweredQuestions = Question.findAllByAnswered(false);
def allAnsweredQuestions = Question.findAllByAnswered(true);


A Map seems like the obvious structure. The keys of the map should be the ids and the values of the Map should be either a List<Boolean> or (probably preferably) a class that encapsulates these 8 booleans.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜