在Grails中保存关联的域类 [英] Saving associated domain classes in Grails
问题描述
class Engine {
字符串名称
int numberOfCylinders = 4
static constraints = {
name(blank:false,nullable:false)
numberOfCylinders(范围:4..8)
}
}
class car {
int year
字符串品牌
引擎引擎=新引擎(名称:默认引擎)
静态约束= {
引擎(可空:假)
品牌(空白:假,可空:假)
年(可空:假)
}
}
这个想法是用户可以在不创建引擎的情况下创建汽车,并且这些汽车会获得默认引擎。在CarController中,我有:
def save = {
def car = new Car(params)
if(!car.hasErrors()&& car.save()){
flash.message =Car saved
redirect(action:index)
} else {
render(view:'create',model:[car:car])
}
}
当试图保存时,我在Car.engine字段上得到一个空值异常,所以显然不会创建和保存默认引擎。我尝试手动创建引擎:
def save = {
def car = new Car(params)
car.engine =新引擎(名称:默认引擎)
if(!car.hasErrors()&& car.save()){
flash.message =Car saved
redirect(action:index)
} else {
render(view:'create',model:[car:car])
}
}
也没有工作。 Grails是否无法保存关联的类?我怎么能实现这样的功能?
我试图保存汽车时得到的例外是
非空属性引用null或
瞬间值
显然,当试图保存时引擎是空的,但为什么?结果你必须这样做:
def car = new Car(params)
car.engine = new Engine(由于引擎不会运行不属于一辆车,你不会得到级联保存/更新/删除,这在我的情况是好的。解决办法是手动保存引擎,然后保存汽车。
I'm struggling to get association right on Grails. Let's say I have two domain classes:
class Engine {
String name
int numberOfCylinders = 4
static constraints = {
name(blank:false, nullable:false)
numberOfCylinders(range:4..8)
}
}
class Car {
int year
String brand
Engine engine = new Engine(name:"Default Engine")
static constraints = {
engine(nullable:false)
brand(blank:false, nullable:false)
year(nullable:false)
}
}
The idea is that users can create cars without creating an engine first, and those cars get a default engine. In the CarController I have:
def save = {
def car = new Car(params)
if(!car.hasErrors() && car.save()){
flash.message = "Car saved"
redirect(action:index)
}else{
render(view:'create', model:[car:car])
}
}
When trying to save, I get a null value exception on the Car.engine field, so obviously the default engine is not created and saved. I tried to manually create the engine:
def save = {
def car = new Car(params)
car.engine = new Engine(name: "Default Engine")
if(!car.hasErrors() && car.save()){
flash.message = "Car saved"
redirect(action:index)
}else{
render(view:'create', model:[car:car])
}
}
Didn't work either. Is Grails not able to save associated classes? How could I implement such feature?
解决方案 For what is worth, I finally nailed it.
The exception I got when trying to save a car was
not-null property references a null or
transient value
It was obvious that the engine was null when trying to save, but why? Turns out you have to do:
def car = new Car(params)
car.engine = new Engine(name: "Default Engine")
car.engine.save()
Since engine doesn't belongs to a Car, you don't get cascade save/update/delete which is fine in my case. The solution is to manually save the engine and then save the car.
这篇关于在Grails中保存关联的域类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!