Augusto Pedraza
Augusto Pedraza

Reputation: 548

Rails route to get a resource using query string

I would like to have a custom route querystring based, to access a specified resource. For example:

/opportunities/rent/san-miguel-de-tucuman?id=45045

That route should map to the action OpportunitiesController#show, with the resource id 45045.

Thanks in advance!!!

Updated

This are my current routes:

So, if I navigate to the /oportunidades/alquiler/san-miguel-de-tucuman?id=123456 route, it go to the Opportunities#index action.

P/S: sorry, I forget to mention that I have a similar route for the index action.

Upvotes: 1

Views: 2346

Answers (3)

Gaurav Gupta
Gaurav Gupta

Reputation: 1191

Make your custom routes as:

resources: opportunities, except: :show

get '/opportunities/rent/san-miguel-de-tucuman/:id' => 'opportunities#show', :as => 'opportunities_show'

and pass your 'id' as opportunities_show_path(id)

EDIT

Change your routes as:

get 'oportunidades/alquiler/san-miguel-de-tucuman/:id' => "opportunities#show", :as => 'opportunities_show'

get 'oportunidades/alquiler/san-miguel-de-tucuman' => "opportunities#index", :as => "opportunities_index"

Now when you want to access your show page just use opportunities_show_path(:id =>123456 )

And for index page use opportunities_index_path

Upvotes: 2

Adrià Carro
Adrià Carro

Reputation: 717

Option 1

Query string parameter

// /opportunities/rent/san-miguel-de-tucuman?id=45045
match '/opportunities/rent/san-miguel-de-tucuman', :to => 'opportunities#show', :as => "show_opportunity", :via => :get

Option 2

Add id like new parameter. More friendly.

// /opportunities/rent/san-miguel-de-tucuman/45045
match '/opportunities/rent/san-miguel-de-tucuman/:id', :to => 'opportunities#show', :as => "show_opportunity", :via => :get

In both cases, you need to call the route like this:

show_opportunity_url(:id => 45045)

In your controller you will get the id in params[:id]

Upvotes: 0

Abhi
Abhi

Reputation: 4261

Use this

match '/opportunities/rent/san-miguel-de-tucuman/:id', :to => 'opportunities#show', :via => :get

and pass a object to the path so created. Eg:-

something_path(@object), here @object is object that with id which will be passed in routes

Upvotes: 1

Related Questions