tags:

views:

297

answers:

3

I'm new to Grails, Groovy and GSP.

I have a domain class "ProductCategory".

class ProductCategory {

    static constraints = {
    }

    static mapping = {
        table 'product_category';
        version false;
        cache usage: 'read-only';
        columns {
            parent column: 'parentid';
            procedure column: 'procid';
        }

    }

    static hasMany = [children:ProductCategory];

    ProductProcedure procedure;
    Integer lineorder;
    String name;
    ProductCategory parent;
    String templatelink;
    char offline;

    String toString() {
        return id + " (" + name + ")";
    }
}

Each category CAN have a parent. I am using an existing database, and the table has a column 'parentid' to do that. When a category has no parent (root level), its parentid is 0.

I have a GSP trying to show data about the parent if any.

<g:if test="${category.parent}">
hello
</g:if>

I was under the impression that this would test for existence. It works fine if the category DOES have a parent, but as soon as parentid=0, it blows up.

No row with the given identifier exists: [ProductCategory#0]

I tried to check for ==0, but it didn't work, I assume because 'parent' is supposed to be an object.

So how can I make it so that it assumes that parentid=0 is the same as parent=null, or NO parent?

Thanks

A: 

parentid should not be equal to 0. It should be null.

What I don't understand in your question, is how can you have parentid == 0 ?

fabien7474
Because this is built over an existing application and database schema. And like I said, in that existing schema, parentid=0 means no parent.
nute
+1  A: 

I think I may have found the answer:

parent column: 'parentid', ignoreNotFound: true;

ignoreNotFound is nowhere on the documentation, but it seems to work!

nute
A: 

You don't need to handle the parentid manually. As soon as you define a domain class like this:

Class Foo {
    Bar bar
}

Gorm/Grails will automatically create a foreign key column for you. And if you define the property nullable:

Class Foo {
     Bar bar
     static constraints = {
         bar(nullable:true)
     }
}

...you can just set it to null and test for null:

def f = new Foo(bar:null)
if (f.bar == null) { ... }
ilikeorangutans
Once again, this application is built on top of an EXISTING DATABASE, with existing data. I cannot let Grails create/modify any database schema for me.
nute