【问题标题】:Saving related entity in grails在grails中保存相关实体
【发布时间】:2013-11-12 14:57:39
【问题描述】:

我在保存来自两个域类的表单值时遇到问题

一类是

 class Ip {

String inetAddress
String dns
String os



String toString(){
    "${inetAddress}"
}

Hoster hoster

static constraints = {
     ....

第二个就是

  class Hoster {

    static HOSTER_OPTIONS = ["Name1", "Name2", "Name3"]
String name;

String toString(){
    "${name}"
}

List ips = new ArrayList()
static hasMany = [ips : Ip]

    static constraints = {
    name(unique: true, blank: false, inList: HOSTER_OPTIONS)
}

我有一个控制器,用于处理来自表单的数据

def systems = new Ip()  
systems.inetAddress = params.ip
systems.dns = params.dns
systems.os = params.os

systems.hoster.name = params.hoster
def result = systems.save(flush: true, failOnError: true)

但我没有管理好数据已保存。

【问题讨论】:

    标签: grails grails-2.0 grails-domain-class grails-controller


    【解决方案1】:

    您没有正确关联控制器中的域类:

    systems.hoster.name = params.hoster
    

    您需要设置数据库中存在的实例,而不是设置名称:

    systems.hoster = Hoster.findByName(params.hoster)
    

    【讨论】:

    • 谢谢!但现在我得到一个不同的错误:Class:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationExceptionMessage:Column 'hoster_id' cannot be null
    • 您的Hoster已经在数据库中了? findByName 返回什么?
    • 是的,主机已经在数据库中了。 findByName 如果存在则返回名称,否则返回 null。
    • 我知道 findByName 的作用,我的问题是关于它在您的上下文中返回的内容:Hoster.findByName(params.hoster)。另外,我的回答有误,请确保您使用的是params.hoster,我写的是“patams”。
    • 我看到了错字并把它改正了。在我的上下文中,它在数据库中时返回主机名称。我做了一个简短的测试来验证: def test = Hoster.findByName("Test")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 2022-08-18
    相关资源
    最近更新 更多