如何更新grails中的外键

时间:2014-08-03 12:21:35

标签: grails gorm

我在域类 Semester 的实例中更新外键时遇到问题。我是Groovy Grails的新人。当我创建新学期时,一切都还可以。

Semester.groovy

class Semester {

    int name
    Season season
} 

Season.groovy

class Season {

    String name
}

SemesterController.groovy

SemesterController{

   def update(){
        def semester = Semester.get(params.id)
        semester.name = params.semester
        semester.season = params.season // Here is a problem !!
        semester.save(flush: true)
        redirect(uri: "/semester/index")
    }
}

edit.gsp

<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="bootstrap-main" />
<title>SARNA</title>
</head>
<body>
    <br />
    <div class="container">
        <g:form class="form-horizontal" role="form"
            url="[resource:semester,  controller: 'Semester']">

            <label for="semester" class="col-sm-2 control-label">Semestr</label>
            <g:textField class="form-control" name="semester"
                value="${semester.name}" />
            <g:select  name="season" from="${com.sarna.entity.Season.list()}" optionKey="id"
                optionValue="name" value="${semester?.season?.id}"/>

            <g:actionSubmit class="btn btn-primary" value="Zapisz"
                action="update" />
        </g:form>

    </div>

</body>
</html>

当我尝试保存更改时,我有以下例外:

URI: /SARNA/semester/index/1
Class: java.lang.IllegalStateException
Message: Cannot convert value of type [java.lang.String] to required type [com.sarna.entity.Season] for property 'season': no matching editors or conversion strategy found

我做错了什么?你可以帮帮我吗?感谢

1 个答案:

答案 0 :(得分:0)

对表单进行以下更改

    <g:form class="form-horizontal" role="form"
        url="[resource:semester,  controller: 'Semester']">

        <g:hiddenField name="id" value="${semester.id}"/>

        <label for="semester" class="col-sm-2 control-label">Semestr</label>
        <g:textField class="form-control" name="name" value="${semester.name}" />
        <g:select name="season.id" from="${com.sarna.entity.Season.list()}" optionKey="id"
            optionValue="name" value="${semester?.season?.id}"/>

        <g:actionSubmit class="btn btn-primary" value="Zapisz"
            action="update" />
    </g:form>

然后,您可以将操作简化为:

SemesterController{

   def update(Semester semester){
        semester.save(flush: true)
        redirect(uri: "/semester/index")
    }
}