简体   繁体   English

如何在 Rails REST API 中使用外部提供的 ID?

[英]How to use externally provided IDs in Rails REST API?

What are the best practices to working with external IDs in REST API in general, and specifically in Rails?一般来说,在 REST API 中使用外部 ID 的最佳实践是什么,特别是在 Rails 中?


Some Background:一些背景:

I created an API for my application, which uses standard resource based JSON REST API.我为我的应用程序创建了一个 API,它使用基于标准资源的 JSON REST API。

I have a Flight model, by which users to create model objects by POSTing to /api/flights.我有一个 Flight 模型,用户可以通过该模型通过 POST 到 /api/flights 来创建模型对象。 This assigns a unique id to the new Flight objects the way ActiveRecord always does.这会按照 ActiveRecord 一贯的方式为新的 Flight 对象分配一个唯一的 id。

So far pretty standard.到目前为止非常标准。

However, my customer wants me to provide an option to assign an id by himself as part of the creation of the Flight object in the API, and later use the id he assigned in order to show/update/delete (etc.) the object by API.但是,我的客户希望我提供一个选项,在 API 中创建 Flight 对象的过程中由他自己分配一个 id,然后使用他分配的 id 来显示/更新/删除(等)对象通过 API。

I figure I can simply add an external_id parameter and add routes to update/delete/index by external_id.我想我可以简单地添加一个 external_id 参数并通过 external_id 添加路由以更新/删除/索引。 However, this seems to clutter the elegant resource based rails approach.然而,这似乎扰乱了优雅的基于资源的 Rails 方法。

So, what's the best practice?那么,最佳实践是什么?

I think this is fine.我认为这很好。 Another similar case is creating a "slug" or "friendly url" for a URL which replaces the less friendly ID ("augments" is a better word than replaces).另一个类似的情况是为替换不太友好的 ID 的 URL 创建“slug”或“友好的 url”(“增强”是比替换更好的词)。 As long as the external_id is immutable, unique within its scope, URL-safe and so on it's equivalent to the ID.只要external_id是不可变的,在其范围内是唯一的,URL 安全等等,它就等同于 ID。 Because it's an external value, however, you need to confirm with your client that it is immutable;但是,因为它是一个外部值,所以您需要与您的客户确认它是不可变的; while possible to have it change, there's a lot of work needed to handle changing the value (especially if it's part of a URL).虽然可以更改它,但需要做很多工作来处理更改值(尤其是当它是 URL 的一部分时)。

If you want to replace Rails' find method to use the external_id instead, use method_missing to redefine id -- there are examples of this around by googling "rails 3 slug method_missing" and similar.如果您想替换 Rails 的 find 方法以使用 external_id,请使用method_missing来重新定义method_missing通过谷歌搜索“rails 3 slug method_missing”和类似方法,可以找到相关示例。

I'm not sure if this can help but you can check the gem friendly id you can specify the external_id to this gem then it'll handle requests我不确定这是否有帮助,但您可以检查 gem友好的 id,您可以为这个 gem 指定 external_id 然后它会处理请求

http://example.com/states/4323454

to be like像是

http://example.com/states/washington

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM