Reputation: 1275
Suppose I have a domain class branch
which has several members:
…
static hasMany = [ members:Member ];
…
Now suppose I want to have the number of members of that branch readily available, to have it displayed in the list
and view
actions, so perhaps storing that information into a variable in the domain class itself would be a good idea?
…
Integer memberCount = members.size();
static constraints = {
memberCount(editable:false);
}
…
(Is this the correct syntax?) Edit: This is not the correct syntax. I cannot assess the size of the members list, as it doesn’t exist yet and grails will complain about size() not being applicable to null objects. What else could I try?
However, as memberCount
is now a variable in the domain class, it is possible to assign a value to it upon creation of the Branch
(which is contra-intuitive) and it will not be updated automatically once a new Member
is added.
It is of course possible to reach the desired result in a different way. I could manipulate the view.gsp
and list.gsp
in the /Branch
directory, add some additional <td>
s there etc. But that does not seem very elegant to me.
Basically, I think what I am looking for is some way to tell grails that a certain variable is derived, should not be setable by the user, but update whenever necessary. Is there such way?
Upvotes: 0
Views: 2661
Reputation: 39580
You can add any property you don't want persisted to the transients
static list:
static transients = ['memberCount']
Also, this StackOverflow question answers the same question
Also, a better way to do derived properties may be to use the Derived Properties feature of GORM
Upvotes: 2