我使用Grails在2.3中引入的REST支持。我的应用包括以下域类:
@Resource(formats=['json', 'xml'])
class Sensor {
String name
static hasMany = [metrics: Metric]
}
@Resource(formats=['json', 'xml'])
class Metric {
String name
String value
static belongsTo = [sensor: Sensor]
}
在UrlMappings.groovy
中,我定义了以下嵌套的RESTful URL映射:
"/api/sensors"(resources: 'sensor') {
"/metrics"(resources: "metric")
}
如果我导航到网址/api/sensors/1/metrics
,我希望响应显示与ID为{1}的所有Metric
个实例,但实际上它会返回所有Sensor
实例(最多10个)
Metric
实例关联的Metric
个实例的网址(未实现我自己的控制器)?Sensor
参数)?答案 0 :(得分:6)
看起来并非如此简单。 :)如果运行此命令,我们可以得到生动的图片:
grails url-mapping-report
看
Controller: metric
| GET | /api/sensors/${sensorId}/metrics | Action: index |
| GET | /api/sensors/${sensorId}/metrics/create | Action: create |
| POST | /api/sensors/${sensorId}/metrics | Action: save |
| GET | /api/sensors/${sensorId}/metrics/${id} | Action: show |
| GET | /api/sensors/${sensorId}/metrics/${id}/edit| Action: edit |
| PUT | /api/sensors/${sensorId}/metrics/${id} | Action: update |
| DELETE | /api/sensors/${sensorId}/metrics/${id} | Action: delete |
因此,我们至少需要MetricController
继承RestfulController
并覆盖index()
来对Metric
进行额外检查,并根据Sensor
返回列表如下图所示:
class MetricController extends RestfulController<Metric> {
static responseFormats = ['json', 'xml']
MetricController() {
super(Metric)
}
@Override
def index() {
def sensorId = params.sensorId
respond Metric.where {
sensor.id == sensorId
}.list()
}
}
以上更改将在点击时为/api/sensors/1/metrics
提供预期结果(包括对分页结果的限制)。