Search code examples
grailsgrails-ormcascade

Disable cascading from dependant to owner


I have a problem with saves cascading to the owner object from the dependant (Book to Library, in this case).

I have two domains like so:

Library {
  String name

  static hasMany = [ books: Book]
}

Book {
  static belongsTo = [ library: Library]
}

And I access them restfully.

Now lets say there are two libraries:

  • id: 1, name: library1
  • id: 2, name: library2

And I have a book that belongs to library-1. I get it like so:

GET /book/1
response: {
  id: 1,
  library: {
    id: 1,
    name: "library1"
  }
}

And then someone updates the book record, assigning it to a different library

PUT /book/1
request body: {
  id: 1,
  library: {
    id: 2,
    name: "library1"
  }
}

And then it will rename the library with id: 2 to name "library1".

  • id: 1, name: library1
  • id: 2, name: library1

I expect it to just get the id of the library from the request, and update the library_id field of the book record.

What should I do?


Solution

  • Since you want to modify the default behavior of the REST functionality within Grails scaffolding you need to implement your own controller(s) to handle this.

    I would recommend you look at what the existing scaffolding creates and modify it to suit your needs. Before you write any further code you would be best off reading the Grails documentation (yes I know there is a lot, but it will save you a lot of work too).