Alex Moreira
Alex Moreira

Reputation: 5

How can I define the name of my id param in a Phoenix member route?

I have a users resource in my router with an extra endpoint for friends like so:

resources "/users", UserController, except: [:create, :delete] do
  get "/friends", UserController, :friends
end

This works, but my friends route is /api/users/:user_id/friends. How can I rename the parameter to id so my route instead becomes /api/users/:id/friends?

Upvotes: 0

Views: 32

Answers (1)

idursun
idursun

Reputation: 6335

I don't think it is possible to change when nesting resources because the nested resources are likely to have their entities with :id parameter so the resources macro is automatically prefixing the parents with their names, hence :user_id

You should be able to achieve what you want by using scope instead of nested resources:

resources "/users", UserController, except: [:create, :delete]

scope "/users/:id" do
  get "/friends", UserController, :friends
end
$ mix phx.routes
GET     /api/users                                 UserController :index
GET     /api/users/:id                             UserController :show
PATCH   /api/users/:id                             UserController :update
PUT     /api/users/:id                             UserController :update
GET     /api/users/:id/friends                     UserController :friends

Upvotes: 0

Related Questions