如何从 Grails 中的控制器访问域属性?
我有以下 Grails 域类:
class Product {
String name
Float basePrice
Category category
String image = "default.jpg"
static constraints = {
name(size:3..25, blank:false)
basePrice(scale:2, nullable:false)
category(inList:Category.list(), nullable:false)
image(blank:false)
}
}
从控制器中,我想获取图像属性的默认值(在本例中为“default.jpg”)。 像这样:
def productInstance = new Product(params)
productInstance.image = getProductPicturePath() ?: Product().image
getProductPicturePath 返回一个图像路径,但如果没有提交图像,控制器应将 null 值替换为默认值。 虽然我当然可以写这样的东西:
productInstance.image = getProductPicturePath() ?: "default.jpg"
它肯定不是很干燥,而且我更愿意将该默认值保留在一处。 我怎样才能实现这个目标?
I have the following Grails domain class:
class Product {
String name
Float basePrice
Category category
String image = "default.jpg"
static constraints = {
name(size:3..25, blank:false)
basePrice(scale:2, nullable:false)
category(inList:Category.list(), nullable:false)
image(blank:false)
}
}
From a controller, I want to get the default value for the image property (in this case "default.jpg"). Something like this:
def productInstance = new Product(params)
productInstance.image = getProductPicturePath() ?: Product().image
getProductPicturePath returns an image path, but in case no image was submitted, the controller shall replace the null value with the default. While I could certainly write something like this:
productInstance.image = getProductPicturePath() ?: "default.jpg"
It's certainly not very DRY, and I would prefer to keep that default value in one place. How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显而易见的解决方案是将其声明为常量,然后引用它。
更好的是,让
getProductPicturePath()
返回默认值。The obvious solution is to declare it as a constant and then refer to it.
Even better, make
getProductPicturePath()
return the default value.如果
params
中没有image
键,将跳过此属性并保留域类中定义的默认值。 因此,假设您的参数不包含
image
键,最简单的方法是对于那些没有图像的产品完全跳过image
属性的分配:If there is no
image
key inparams
will skip this property and leave the default value defined in the domain class. So, assuming that your params doesn't contain an
image
key, the simplest way would be to skip the assignment of theimage
property at all for those products that have no image: