Grails的 - 无法孩子记录添加到父(Grails - Can't add child

2019-11-01 07:01发布

试图追随所示的例子在这里我想创建可链接到父记录的记录。

在我来说,我有两个类:传感器,和读物。 我可以没有任何问题创造传感器,但无论我如何努力创造读数我忽视了:(

我一直在纺纱我的车轮足够长的时间,我扔在毛巾,希望有人能发现我的愚蠢的错误(或多个)。

还有一两件事 - 我要发布使用JSON数据。 但通过调试过程中,我甚至不看JSON值,我硬编码他们,它仍然无法正常工作。

ReadingsController.groovy

package grailshelloworld

import grails.converters.JSON
import groovy.json.JsonSlurper

class ReadingsController {

    def scaffold=Readings

        def save = {

                def slurper = new JsonSlurper()
                def result = slurper.parseText(request.reader.text)

                def s = new Sensor (sensorid: "SID", sensorname: "name", sensordescription: "description")
                        .addToReadings(reading: "blah")
                        .save()

                render ([ok: false] as JSON)


    }
}

sensor.groovy

package grailshelloworld

class Sensor {

    String sensorid
    String sensorname
    String sensordescription

    static hasMany = [readings: Readings]

    static constraints = {
        sensorid blank:false, nullable: false 
        sensorname blank:false, nullable: false
    }
}

Readings.grooovy

package grailshelloworld
import java.util.Formatter.DateTime;
class Readings {
    String reading
    static belongsTo = [sensor: Sensor]
}

当前的错误:参数类型不匹配......

<dt>Class</dt><dd>java.lang.IllegalArgumentException</dd><dt>Message</dt><dd>argument type mismatch</dd></dl><h2>Around line 15 of <span class="filename">grails-app/controllers/grailshelloworld/ReadingsController.groovy</span></h2>
<pre class="snippet"><code class="line"><span class="lineNumber">12:</span>     def slurper = new JsonSlurper()</code><code class="line"><span class="lineNumber">13:</span>        def result = slurper.parseText(request.reader.text)</code><code class="line"><span class="lineNumber">14:</span></code><code class="line error"><span class="lineNumber">15:</span>     def s = new Sensor (sensorid: &quot;SID&quot;, sensorname: &quot;name&quot;, sensordescription: &quot;description&quot;)</code><code class="line"><span class="lineNumber">16:</span>           .addToReadings(reading: &quot;blah&quot;)</code><code class="line"><span class="lineNumber">17:</span>          .save()</code><code class="line"><span class="lineNumber">18:</span></code></pre><h2>Around line 195 of <span class="filename">PageFragmentCachingFilter.java</span></h2>

Answer 1:

你必须明确地创建一个新的尝试过Readings

def s = new Sensor (sensorid: "SID", sensorname: "name", sensordescription: "description")
                    .addToReadings(new Readings(reading: 'blah'))
                    .save()

该错误是说:“大约15线”,这是开始到def s = ...发言。

我知道文档说是可以做到的,你尝试的方式 - 但它是值得一试。



文章来源: Grails - Can't add child record to parent
标签: grails gorm