开发者

Multiple dynamic method calls or declaring a variable in Grails

In my view, if I have a situation where I need to use a开发者_高级运维 dynamic method (such as Domain.findByName("name")) in multiple places, would it be better to define a variable with and refer to that, rather than have the dynamic method in multiple places? I know this seems like an obvious answer, but I just wanted to make sure Grails doesn't cache it or something, and indeed two DB calls are being made.


By default, grails will only cache "get" requests (i.e. Book.get(4)), if you don't set up any additional caching, you'll hit the database for each request (as you're seeing).

See the 'caching queries' section of the grails documentation for more detail.

If you only want the call to be made once (which makes sense in a view since you'd want it to be consistent), I'd either do the query in the action and pass it in the model, or else you could also use the g:set in your view to set it (though this sounds like it's more appropriate for a controller or service).


It would be better to send the domain object to the view as part of the model, rather than calling Domain.findByName("name") from your view.

So in your controller method you'd want

def myAction = {
    def myObject = Domain.findByName("name")
    // do other stuff
    [myObject: myObject]
}

then in your view you can access it by

${myObject.property}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜