Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add constraints on inherited properties in a grails domain sub-class

Tags:

Here's what I'd like to do:

class A {   String string   static constraints = {     string(maxSize:100)   } }  class B extends A {   static constraints = {     string(url:true)   } } 

So class A should have some constraints and B should have the same plus additional constraints on the same property.

I couldn't get that to work though and I can imagine that it would clash with the Table-per-Hierarchy concept.

So I tried to work around that problem by introducing a Command object with class B's constraints which can be validated in the constructor of class B. However it seems that Command objects can only be used within controllers (grails keeps saying that there is no .validate() method for it).

So my question is: What is the most elegant way to solve this using grails constraints (not re-implementing the validation manually)? Could be...

  • Switching to Table-per-Sub-Class concept?
  • Making the Command Object work in the Domain class somehow?
  • Any other way?

Edit: It would be okay for me to define all the constraints in the child classes, repeating the constraints of the parent class or not even having constraints in the parent class at all. But the solution should work for multiple child classes (with different constraints) of the same parent class.

like image 254
Jörg Brenninkmeyer Avatar asked Oct 14 '10 14:10

Jörg Brenninkmeyer


2 Answers

You can use

    class B extends A {        static constraints = {           importFrom A           //B stuff        }     } 

as states in http://grails.org/doc/latest/ref/Constraints/Usage.html

like image 126
RoberMP Avatar answered Sep 20 '22 06:09

RoberMP


The way it was in 2.x:

As constraints is a closure executed by some ConstraintsBuilder, I'd try calling it from B, like

class B extends A {    static constraints = {      url(unique: true)     A.constraints.delegate = delegate  # thanks Artefacto     A.constraints()   }  } 
like image 27
Victor Sergienko Avatar answered Sep 18 '22 06:09

Victor Sergienko