简体   繁体   English

从 id 或其他唯一字段获取 Rails 资源的正确方法?

[英]Correct way to GET a Rails resource from their id or other unique field?

We have an API where we can GET a user in two ways:我们有一个 API ,我们可以通过两种方式获取用户:

  1. Through his default Rails-generated id (unique, autoincrement)通过他默认的 Rails 生成的id (唯一,自动增量)
  2. Through a unique field employee_id (the ID of the employee in an external system, we don't have related employee controller/model/table)通过一个唯一的字段employee_id (外部系统中的员工ID,我们没有相关的员工控制器/模型/表)

Here's how it's exposed as URIs:以下是它作为 URI 公开的方式:

/users/:id
/users/employee_id/:employee_id

Both sends the call to the users#show method that will look for either params[:id] or params[:employee_id] and then return the user if it exists.两者都将调用发送到users#show方法,该方法将查找params[:id]params[:employee_id] ,然后返回用户(如果存在)。

I can't really tell why, but the second URI feels wrong.我真的不知道为什么,但第二个 URI 感觉不对。

What is a standard or better way to access a ressource from different unique IDs?从不同的唯一 ID 访问资源的标准或更好的方法是什么?

We're thinking of doing this using two calls (first to index to get users matching the employee_id , then to show to retrieve the user info from the id we got), but I'm curious about alternatives.我们正在考虑使用两个调用来执行此操作(首先index以获取与employee_id匹配的用户,然后show以从我们获得的id检索用户信息),但我对替代方案感到好奇。

It's not very restful looking.看起来不是很安静。

Could try something like this...可以试试这样的...

Add a non-resource route...添加非资源路由...

get 'employees(/:employee_id)', to: 'users#employee'

add an employee action to your users controller, which will look up the user by the supplied id向您的用户 controller 添加employee操作,这将通过提供的 id 查找用户

  def employee
    @user = User.find_by(employee_id: params[:employee_id])
    render json: @user
  end

and now you have a restful looking API现在你有一个看起来很安静的 API

/users/:id
/employees/:employee_id

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

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