smeeb
smeeb

Reputation: 29517

Configuring Rails endpoints with specific HTTP verbs and path params

I have a simple Rails application and would like to expose an GET endpoint at:

GET http://localhost/widgets/{widget_id}/{fizz_id}

I'm wondering how I can setup the expectation for that endpoint (with {widget_id} and {fizz_id} as path params) in my routes.rb and/or the controller, say, WidgetsController?

I know you can access params inside controllers, but I think that only gives you access to form parameters and/or query string parameters. Here, those IDs are part of the RESTful path, and I'm wondering:

  1. How to configure things so that the endpoint is actually: GET http://localhost/widgets/{widget_id}/{fizz_id}; and
  2. How to get access to the values of those IDs from inside a controller method/action; and
  3. Specifying this endpoint is for GET verbs only

Upvotes: 0

Views: 119

Answers (2)

Peter Lohmann
Peter Lohmann

Reputation: 11

You can find everything you have to know about Rails routing here:

http://guides.rubyonrails.org/routing.html

In your routes.rb put a line like this:

get '/widgets/:widget_id/:fizz_id', to: 'widgets#show'

In your WidgetsController:

def show
  execute(params[:widget_id], params[:fizz_id])
end

Upvotes: 1

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

how I can setup the expectation for that endpoint (with {widget_id} and {fizz_id} as path params) in my routes.rb

# routes.rb
get '/widgets/:widget_id/:fizz_id', to: 'widgets#action'
# widgets_controller.rb
def action
  widget_id = params[:widget_id] # <- value of /:widget_id
  fizz_id   = params[:fizz_id]   # <- value of /:fizz_id
end

For more info read the documentation.

Upvotes: 2

Related Questions