Andy Sanchez
Andy Sanchez

Reputation: 197

Ruby on Rails Routing for Wildcard URL

I was trying to pull a segment from the URL and since I'm a rookie, kind of confused by the routing.

My code to get the last segment works fine, it's my routing that is messed up.

Ideally the URL would like this:

http://localhost.com/track/item/1234

I'm using Rails v4.0.8 & Ruby v2.0.0p451

The error is No route matches [GET] "/track/item/1234"

Here's the whole routes.rb file:

SepContact::Application.routes.draw do

  get "track/item"
  get "track/item/:id"  
  get "contacts/contact"
  resources "contacts", only: [:new, :create]

end

Upvotes: 0

Views: 749

Answers (2)

nPn
nPn

Reputation: 16728

I think CWitty's should work as well but here is a more explicit format.

  match "track/items",      to: 'controller#index', via: :get, as: "items"
  match "track/items/:id",  to: 'controller#show', via: :get, as: "item"

Note I updated your url to be more rails like items rather than item

I think most of your problem is with the track segment of the url. I don't see how get 'track/items' would map the the items#index controller / method I think the match method would be needed here to explicitly map the url to the correct controller and method.

Is there a good reason you are naming you url like that?

You can read all about routing here: http://guides.rubyonrails.org/routing.html

Here is the section of the above document that discusses using the match method:

3.7 HTTP Verb Constraints In general, you should use the get, post, put, patch and delete methods to constrain a route to a particular verb. You can use the match method with the :via option to match multiple verbs at once:

match 'photos', to: 'photos#show', via: [:get, :post]

You can match all verbs to a particular route using via: :all:

match 'photos', to: 'photos#show', via: :all

Routing both GET and POST requests to a single action has security implications. In general, you should avoid routing all verbs to an action unless you have a good reason to.

Upvotes: 1

CWitty
CWitty

Reputation: 4526

Your routes should be like:

SepContact::Application.routes.draw do

  get "track/item/:id", to: 'controller#action'
  get "track/item", to: 'controller#action' 
  get "contacts/contact" to: 'controller#action' 
  resources :contacts, only: [:new, :create]

end

You need to specify a to: pointing to a controller and action unless you use the resource or resources helper.

Upvotes: 1

Related Questions