开发者

Grails: derived fields in domain classes

开发者 https://www.devze.com 2023-04-08 04:23 出处:网络
Suppose I have a domain class branch which has several members: … static hasMany = [ members:Member ];

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 cre开发者_Python百科ation 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?


You can add any property you don't want persisted to the transients static list:

static transients = ['memberCount']

See this page in the manual

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号