Daddy Pumpkin
Daddy Pumpkin

Reputation: 484

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:

Upvotes: 0

Views: 1483

Answers (2)

blacktide
blacktide

Reputation: 12076

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.

Upvotes: 1

Mario David
Mario David

Reputation: 1615

You can implement getProfilePicture as following:

String getProfilePicture() {
    Picture.where { user == this && profile == true}.first().url
}

Alternatively you can use a dynamic Finder (as shown in the comments). By the way: the Picture Class does not need to create the user Attributes twice. static belongsTo = [user: User] is enough.

Upvotes: 1

Related Questions