【发布时间】:2015-12-10 15:13:15
【问题描述】:
在我的 Rails 4 应用程序中,我有以下模型:
class Location < ActiveRecord::Base
has_many :location_parking_locations
has_many :parking_locations, through: :location_parking_locations
end
class LocationParkingLocation < ActiveRecord::Base
belongs_to :location
belongs_to :parking_location
end
class ParkingLocation < ActiveRecord::Base
has_many :location_parking_locations
has_many :locations, through: :location_parking_locations
end
对路线/locations/1/parking_locations 的调用返回位置= 1 的停车位置集合。响应中的一些属性来自连接模型(location_parking_location)。例如,响应中的其中一个 park_locations 可能如下所示:
{
id: 1
name: 'Test Parking Location'
description: 'Test description for the parking location'
upvote_count: 10, <- this field comes from the join model
downvote_count: 8, <- this field comes from the join model
}
如果用户想要更新直接来自停车位置的属性,例如名称,我觉得他们应该能够通过将停车位置视为主要资源的端点来执行此操作,而不是而不是必须将其作为特定位置的子资源来引用。例如,他们应该能够从端点/parking_locations/1 编辑或检索停车位置,而不是特定于某个位置。
在这种情况下,不应包含来自 location_parking_location 的字段,例如 upvote_count 和 downvote_count。
是否有某种设计模式允许这种行为?还是我应该以不同的方式思考这个问题?例如,也许在检索端点locations/1/parking_locations 时,我不应该返回parking_locations 的集合,而是应该返回location_parking_locations 的集合,其中可以包含一个表示来自parking_location 的属性的对象。在这种情况下,端点是否应该更改为locations/1/location_parking_locations?例如,响应中的一个对象可能如下所示:
{
id: 9
upvote_count: 10,
downvote_count: 8,
parking_location: {
id: 1
name: 'Test Parking Location'
description: 'Test description for the parking location'
}
}
在这种情况下,有人会如何添加新的停车位?是否可以通过发布到/parking_locations 端点来完成?或者他们应该同时创建它并将其添加到一个位置,也许通过发布到/locations/1/parking_locations?
在这种情况下,如果有人想将已经存在的停车位置添加到某个位置怎么办?在那种情况下,也许他们应该 PUT 到/locations/1/parking_locations/{parking_location_id}?
【问题讨论】:
标签: ruby-on-rails rest