FrancescoDS
FrancescoDS

Reputation: 995

grails: create entry in database from controller

I have two domain classes, A and B. B class belongs to A class. I want that, when A object is created, a B object is automatically created too and added into the related db table (with the id value of the A object). Is it possible? How can I do it?

I've tried doing the following (in A controller):

def b = new B();

    b.a = aInstance;

    if(!b.save(flush: true)){
        flash.message = "error"
        return
    }

but b.save() always fails...

EDIT: it seems that the problem is that some field is required. the class B is as follows:

class B {

int field1;
int field2;
String field3;

static belongsTo = [anstances:A]
static constraints = {
}

}

Why do the fields field1 and field2 are required?

EDIT2: I've changed type of int fields to String. Now they are not required, but save() returns null and i see the "error" label

Upvotes: 0

Views: 100

Answers (1)

Gregg
Gregg

Reputation: 35904

Based on your edit, the saving issue is because you haven't specified a constraint on your properties and fields are nullable: false by default. From the documentation:

nullable: Allows a property to be set to null - defaults to false.

Upvotes: 1

Related Questions