简体   繁体   中英

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:

  1. Through his default Rails-generated id (unique, autoincrement)
  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)

Here's how it's exposed as URIs:

/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.

I can't really tell why, but the second URI feels wrong.

What is a standard or better way to access a ressource from different unique IDs?

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.

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

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

and now you have a restful looking API

/users/:id
/employees/:employee_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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