Reputation: 3685
I'm new to Grails and I have two domain classes like this:
class User {
String username
String password
static hasMany = ['boards':Board]
static belongsTo = ['belongsToBoard':Board]
}
class Board {
String message
boolean starred
}
Now I want the constraints like "User
can have a board
with message
being unique"(Note that I don't want Board
to be unique, but for each User
, the message
should be unique. Example:
User : batman
Board: test,test (messages)
is not valid, where as:
User: batman
Board: test
User: batgirl
Board: test
is valid one.
Is it possible to do so in the grails constraints
block? If not how should I do this?
Thanks in advance.
Upvotes: 0
Views: 97
Reputation: 75671
Your belongsTo
property is unusual - if this is a one-many, i.e. a User has many Boards, then the belongsTo
goes on the Board side. This enables cascaded deletes and also only uses two tables; if the relationship isn't bidirectional you get a third to manage the relationship. If it's a many-to-many then you're missing the hasMany
in Board.
If it is a one-many and you put this in Board
static belongsTo = [user: User]
then you can put a 2-column unique constraint in Board:
static constraints = {
message unique: 'user'
}
This is described in the docs on the right in the "Constraints" section under "unique".
Upvotes: 1