Skip to content

Instantly share code, notes, and snippets.

@joeRinehart
Created August 25, 2012 21:17
Show Gist options
  • Select an option

  • Save joeRinehart/3471073 to your computer and use it in GitHub Desktop.

Select an option

Save joeRinehart/3471073 to your computer and use it in GitHub Desktop.
GrailsModelsPart3
package recordstore
class Album {
// Mappings
static hasMany = [
songs : Song,
artists : Artist
]
// Properties
String name
List songs
static constraints = {
}
}
package recordstore
class Artist {
String name
static hasOne = [
biography : Biography
]
static constraints = {
biography( unique: true )
}
}
package recordstore
class Artist {
String name
static hasOne = [
biography : Biography
]
static belongsTo = [
album : Album
]
static hasMany = [
album : Album
]
static constraints = {
biography( unique: true )
}
}
@Test
void artistHasOneBiographyShouldCascadeSaves() {
def originalBiographyCount = Biography.list().size()
// Create a bio
def bio = new Biography( content: "Two guys and friends from Concord, NC")
// Create an artist
def artist = new Artist( name: "The Avett Brothers", biography : bio )
// References should be set up
assert artist.biography == bio
assert bio.artist == artist
// Saving album should save song
assert !bio.id
artist.save()
assert Biography.list().size() == originalBiographyCount + 1
assert bio.id
}
@Test
void artistIsManyToManyAlbum() {
// Note that we save from the 'owning' side!
def originalArtistCount = Artist.list().size()
def album = new Album( name : "Chimes of Freedom")
.addToArtists( new Artist( name : "The Avett Brothers", biography : new Biography( content: "Two guys etc." ) ) )
.addToArtists( new Artist( name : "Johnny Cash", biography : new Biography( content: "A man in 0x000000." ) ) )
.save()
assert album.id
assert Artist.list().size() == originalArtistCount + 2
}
package recordstore
class Biography {
static belongsTo = [
artist : Artist
]
String content
static constraints = {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment