Fetch random GORM model
Despite busy schedule at work and a year old daughter at home, who now requires constant attention, I was able to get some time to work on the Grails community site (Grails Crowd).
As a part of it, I wanted to have a feature to display a 'random' user (a 'member') In fact, keep displaying a random user as long as 'Discover users' link is being clicked. You know, kind of like Flickr's "Explore" feature. So with a help of standard JDK library features i.e. 'java.utils.Collections.shuffle()' and Groovy closures, here's what I've come up with:
MemberController's action:
...
def findRandom = {
def member = null
withMemberIds { memberIds ->
//Pick the last one
member = Member.get(memberIds[-1])
//Then remove it from the list
memberIds.pop()
}
if(member) {
render(view: 'discover', model: [member: member])
}
else {
//No one is registered yet - just 'go home'
redirect(uri:'/')
}
}
private def withMemberIds(closure) {
def memberIds = session.memberIds
if (!memberIds) {
memberIds = Member.withCriteria {
projections {
property('id')
}
}
if (!memberIds.isEmpty()) {
//Some members are in the database:
//Shuffle 'em up
Collections.shuffle(memberIds)
session.memberIds = memberIds
}
else {
//No members are in the database
return
}
}
closure(memberIds)
if (memberIds.isEmpty()) {
session.memberIds == null
}
}
...
It works like a charm.
Later...

0 comments:
Post a Comment