asdfkjasdfjk
asdfkjasdfjk

Reputation: 3894

Extract params fro url in rails

From the url below how can I extract the value 1?

`http://localhost:3000/category/products/1`

I tried params[:id] and params[:products][:id] but got nothing.

Upvotes: 0

Views: 55

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Routes

The direct answer to your question is to fix your routes.rb file

As per the Rails RESTful routing structure, you should be able to use a named scope to achieve this:

#config/routes.rb
scope 'category' do
    resources :products
end

#/category/products/1 -> params[:id]

Nested

What I recommended above should fix your problem directly

However, I think you're trying to achieve nested resources. If this is the case, you should use something like this:

#config/routes.rb
resources :categories do 
    resources :products
end

This will allow you to do:

#categories/:id/products/:product_id

Upvotes: 0

Peeyush
Peeyush

Reputation: 6454

Did you make suitable change in your routes.rb file? You need to include something like

GET /category/products/:id , ...

to make it work with params[:id].

Upvotes: 1

Related Questions