问题
Trying to follow the example shown here I am trying to create a record which links to a parent record.
In my case I have two classes: Sensor, and Readings. I can create Sensors without any issues, but no matter how I try to create readings I seem to fail :(
I've been spinning my wheels for long enough, I'm throwing in the towel and hoping someone can spot my silly mistake(s).
One more thing - I want to post the data using JSON. But through the debugging process I'm not even looking at the JSON values, I've hard coded them and it still doesn't work.
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]
}
Current error: argument type mismatch...
<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: "SID", sensorname: "name", sensordescription: "description")</code><code class="line"><span class="lineNumber">16:</span> .addToReadings(reading: "blah")</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>
回答1:
Have you tried it by explicitly creating a new Readings
?
def s = new Sensor (sensorid: "SID", sensorname: "name", sensordescription: "description")
.addToReadings(new Readings(reading: 'blah'))
.save()
The error is saying "around line 15" which is the start to the def s = ...
statement.
I know the docs say it can be done the way you are attempting - but it's worth a try.
来源:https://stackoverflow.com/questions/13886331/grails-cant-add-child-record-to-parent