Search code examples
grailsgsp

getting an object by id in a GSP file


Part of my domain model has Conversation which has many ChatMessages

In my index.gsp I have the following :

<g:each in="${allConversations}" var="conversation">
        ${conversation.chatMessages}
    </g:each>

to display all conversations of a particular user, which outputs the chat messages as

[hi, how are you][another convo, hi again]

which is the correct results. But I only want to get the first message of each conversation. I have tried

${conversation.chatMessages[0]}

and

${conversation.chatMessages.get(0)}

but to no avail. What is the correct syntax for this?


Solution

  • If you want to be able to refer to individual messages within the conversation by index then you need to declare the association as a List:

    class Conversation {
      static hasMany = [chatMessages: ChatMessage]
    
      List chatMessages
    
      // constraints, mapping, other properties...
    }
    

    If you have only the hasMany without the List chatMessages then the association will be mapped as a Set rather than a List, which lets you iterate but not access by index.

    See sets, lists and maps in the grails docs for full details.