Bart
Bart

Reputation: 17361

GORM how to ensure uniqueness of related objects property

I'm trying to get my head around GORM and relational mapping. The relationships are working fine but there is one problem. I can't seem too ensure that every MailAddress added to MailingList has a unique address. What would be the must efficient way to do this?

Note: There is no unique constraint on MailAddress.address. Identical addresses can exist in the same table.

class MailAddress {

    String name
    String email

    static belongsTo = MailingList

    static constraints = {
        name blank:true
        email email:true, blank:false
    }
}

class MailingList {

    String name

    static hasMany = [addresses:MailAddress]

    static mapping = {
        addresses cascade: 'all-delete-orphan'
    }

    static constraints = {
        name blank:false
    }
}

Upvotes: 0

Views: 412

Answers (2)

Bart
Bart

Reputation: 17361

As mentioned in the comments by @ibaralf the answer is a custom validator. The MailingList class needed to validate if all addresses (MailAddress) have a unique e-mailaddress.

I added this constraint to the MailingList class and it worked.

static constraints = {
    name blank:false

    addresses(validator: {

        if (!it) {
            // validates to TRUE if the collection is empty
            // prevents NULL exception
            return true
        }

        // Grab a collection with all e-mailaddresses in the list
        def addressCollection = it*.email
        // Compare to a collection with only unique addresses
        return addressCollection == addressCollection.unique()
    })
}

More info can be found here http://grails.org/doc/2.2.0/ref/Constraints/validator.html

Upvotes: 1

ibaralf
ibaralf

Reputation: 12518

There is a unique constraint you can add:

static constraints = {
    name blank:true
    email email:true, blank:false, unique: true
}

=> put the unique constraint on the email variable (unique: true). This would prevent identical email addresses to be saved in the table.

Upvotes: 0

Related Questions