views:

401

answers:

1

I have roughly the following in my grails 1.1 app

class AppCategory {
    static belongsTo = App
    static hasMany   = [ apps: App ]
    String name
}

class App {
    static hasMany = [ categories: AppCategory]
    String name
}

App app = new App()
AppCategory appCat = AppCategory.findByName('blah')
app.addToCategories(appCat)
app.save()

The correct tables (app, app_category and app_categories) are created and the columns all seem fine, but I don't end up with any records in the association table and no errors. The app_category table and app table are correctly populated.

Do I need to manually manage a domain object for the association table? Or better yet, am I just missing something totally obvious?

+5  A: 

Well, one thing that isn't represented in your example above is that you didn't give a name to your App instance, even though it's a required field (grails fields are nullable:false by default unless you explicitly tell it otherwise). I bet if you check

app.hasErrors()

After your app.save(), that you'll see it does have errors that you can list in the app.errors collection.

Otherwise, what you have is fine, and this code worked fine for me with the domain objects you have above:

AppCategory appCat = new AppCategory(name: "blah")    
appCat.save()    
assert !appCat.hasErrors()


App app = new App(name: "testApp")
app.addToCategories(appCat)    
app.save()    
assert !app.hasErrors()
Ted Naleid