views:

93

answers:

2

I've been stuck on this for a day now! I'm just getting started with Grails/Groovy.

I have two Domain classes with a simple Many-to-one foreign key. Simplified a bit, they are "Company"

class Company {

    String name
    String city
    String state
    String ticker

    static constraints = {
        name(unique:true, maxSize:40)
        state(blank:true, maxSize:2)
        city(blank:true, maxSize:40)
        ticker(blank:true, maxSize:8)
    }
}

and Signer (who may belong to a Company)

class Signer {

    String firstName
    String lastName
    String city
    String state
    String zip
    String email
    Company company

    static constraints = {
        firstName(maxSize:40, blank:false)
        lastName(maxSize:40, blank:false)
        city(maxSize:40, blank:false)
        state(maxSize:2, blank:false)
        zip(maxSize:5, blank:false)
        email(maxSize:50, unique:true, email:true, blank:false)
        company(nullable:true)
    }
}

Here's the problem:

I can't figure out how to insert a new record into "Signer" and get the company field to contain the value of a company_id.

mysql> select * from signer;
+----+---------+-----------+------------+----------------------+------------+-----------+-------+-------+
| id | version | city      | company_id | email                | first_name | last_name | state | zip   |
+----+---------+-----------+------------+----------------------+------------+-----------+-------+-------+
|  1 |       0 | Sunnyvale |       NULL | [email protected] | Robert     | Swirsky   | CA    | 94087 | 
|  2 |       0 | Sunnyvale |       NULL | [email protected] | Robert     | Swirsky   | CA    | 11111 | 
|  3 |       0 | Sunnyvale |       NULL | [email protected] | Robert     | Swirsky   | CA    | 11111 |

I've tried the following:

   def s = new Signer(params)
   s.save()

where params contains:

*company_id* set to the # of an existing company record

company set to the # of an existing company record an instance of a

Company domain object set by c = Company.get(id) // where id is the # of a valid company params.company = c

I also tried this with

params.company_id = c

None of these work! When I look at the table in mysql, the company_id column is always null.

How do I get this to work? Hibernate is trying to be "too smart" here! I just want to shove a record number into company_id!

A: 

To your Signer class try adding:

 static belongsTo = Company

Among other things, if the corresponding company record is deleted, so will the signer.

Sean A.O. Harney
Wouldn't you do that only for a one-to-one relationship and not for a many-to-one relationship?
ראובן
+1  A: 

The bind param should be company.id instead of company_id.

John Wagenleitner
That's it! Thanks
ראובן