Search code examples
grailsgroovygrails-orm

Grails findBy query with foreign key


I'm trying to fetch a user profile picture from the DB by calling the getProfiePicture() method on User object.

Method call from view:

<p>${user.getProfilePicture()}</p>

User.groovy domain class:

class Picture {

  User user
  String url
  boolean profile = false
  boolean verified = true
  
  static belongsTo = [user: User]

  static constraints = {
  }
}

Picture.groovy domain class:

class User {
  
  static hasMany = [pictures: Picture]

  String uid = UUID.randomUUID().toString()
  String username
  String password

  String getProfilePicture() {
    log.debug("ID: " + id)
    log.debug("UID: " + uid)
    log.debug("Pictures: " + pictures)
    return Picture.findByUserIdAndProfile(id, true)
  }
  
}

Picture table: enter image description here

Problem

I'm getting this error when I'm trying to get the profile picture:

Class
org.codehaus.groovy.grails.exceptions.InvalidPropertyException
Message
No property found for name [userId] for class [class foo.Picture]

What am I doing wrong?

I'm using:

  • Grails 2.4.4

Solution

  • The getProfilePicture() method inside your User domain class should return the following:

    Picture.findByUserAndProfile(this, true)
    

    The reason you're getting that error is because you are trying to find a Picture instance by userId, a field which doesn't exist.