0

I have 2 domain classes

class a {
    String name
    static constraints = {
        name unique:true
    }
}

class b {
    String description
}

and in domain class b I want to call class a

import a
class b {
    String description
    static constraints = {
         description unique:'a.name'
    }
}

and get error

Scope for constraint [unique] of property [description] of class [b] must be a valid property name of same class

How do I get a property from class a to b?

doelleri
  • 19,232
  • 5
  • 61
  • 65
rsijaya
  • 159
  • 2
  • 14

2 Answers2

1

You need to write a custom validator to check the uniqueness since it relies on more information than the single instance of b will have.

Something like

static constraints {
     description validator: { val ->
         !a.findByName(val)
     }
}

might do the trick.

doelleri
  • 19,232
  • 5
  • 61
  • 65
  • the val is refer to description, is not working, because i need to make description unique based on name class a, example name="1" description="1" true, name="2" description="1" true, name"1" description="1" false, anyway thanks your help. – rsijaya Mar 13 '13 at 03:05
1

Assuming you try to do this in Grails 2+

You can't use validation that way. In your example you need to reference to a property of the same domain class. To correct the constraint in class B you can write:

class B {
    String description
    static contraints = {
        description unique:true
    }
}

But I think you want to import the constraints from class a which is done like this.

class B {
    String description
    static contraints = {
        importFrom A
    }
}

See http://grails.org/doc/latest/guide/validation.html#sharingConstraints

This will import all constraints on properties that the two classes share. Which in your case is none.


UPDATE

I got a similar question and found a solution for it. So I thought to share it here with you. The problem can be solved with a custom validator. In your case constraints for class B:

static constraints = {

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

        def names = A.findAll()*.name
        return names == names.unique()
    })
}

It's difficult to answer your question correctly since the requirements are a bit odd. But maybe it will help.

Bart
  • 17,070
  • 5
  • 61
  • 80
  • yes i use grails 2.1.1, i just need validate description must unique based on class a.name, thanks – rsijaya Mar 13 '13 at 04:53
  • I have the same question here http://stackoverflow.com/questions/15371949/gorm-how-to-ensure-uniqueness-of-related-objects-property I will let you know if I find a solution – Bart Mar 13 '13 at 05:56
  • I keep coming back to the link in this post - thanks! – pherris Mar 20 '15 at 16:12