0

From a list of GORM database objects that are ordered desc in my user domain model I want to order them asc (i.e., in reverse order in the view). For example to get the latest books of a user from the database, but insert them in the Dom in reverse order where the latest book comes last.

How do I perform a reverse each in my GSP?

Controller:

def books = user.books

GSP:

<g:each in="${books}" var="book">${book}</g:each>
Michael
  • 32,527
  • 49
  • 210
  • 370

2 Answers2

3

You can use default sort for relation collection as described here. So if you define like this:

class User {
    …
    static hasMany = [books: Book]
    static mapping = {
        books sort: 'publishDate', order: 'asc'
    }
}

The collection will be sorted on database level

Mr. Cat
  • 3,522
  • 2
  • 17
  • 26
2

<g:each in="${books.reverse()}" var="book">${book}</g:each>

EDIT

Got carried away :). I would rather suggest:

def books = user.books?.reverse() in controller.

(Separation of concern, view should not have logic of manipulating model)

UPDATE:

In case books are not ordered in User, explicit sorting is required.

def newestBooks = user.books?.asList().sort{it.publishDate}

to reverse sort use

def newestBooks = user.books?.asList().sort{-it.publishDate}

dmahapatro
  • 49,365
  • 7
  • 88
  • 117
  • I disagree, the model implies no order. Tables are not ordered. In my opinion, the order in which objects display is part of the logic of the view. – James Kleeh May 08 '13 at 01:05
  • If I have `def newestBooks = user.books?.reverse()` set to model? – dmahapatro May 08 '13 at 01:10
  • This is not working because there is no order in the domain class. – Michael May 08 '13 at 01:28
  • The question says the objects are ordered desc in `user` domain. If that is not the case then it has to be sorted in the controller as shown in the update above in the answer. – dmahapatro May 08 '13 at 01:41