我正在使用 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")
}
如果我导航到 URL
/api/sensors/1/metrics
我希望回复显示所有 Metric
与 Sensor
关联的实例ID 为 1,但实际上它返回所有 Metric
实例(最多 10 个)Metric
与特定 Sensor
相关联的实例实例(没有实现我自己的 Controller )? max
参数)? 最佳答案
好像没那么简单。 :) 如果运行这个命令,我们可以得到一个生动的画面:
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
提供预期结果(包括对分页结果的限制)打的时候。
关于rest - 嵌套的 RESTful 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22675247/