user2963365
user2963365

Reputation: 91

Routing with Parameters in Ruby on Rails

I'm new to rails, and I'm struggling with handling the routing correctly. Right now I have a link called "details," and when the user clicks on it I would like the method "view_details" (within the pages controller) to be called with a location parameter that I'm passing in:

<%= link_to "Details", :controller => "pages", :action => "view_details", 
:location =>  v["coordinates"]%>

In my routes.rb file, I have:

get 'pages/view_details/:location', to: 'pages#view_details'

I am getting the following error: No route matches [GET] "/pages/view_details/latitude=37.3505570824247&longitude=-121.922104884669"

When I rake routes, I see this (with no prefix):

How can I fix this?

Upvotes: 4

Views: 12610

Answers (1)

Gerry
Gerry

Reputation: 10507

The problem is that you are passing a hash as a value for location parameter so, instead of just adding one parameter (i.e. location), it adds two parameters (i.e. latitud and longitude) and your routing fails.

To fix this you could set your route without location, like this:

get 'pages/view_details', to: 'pages#view_details'

Now, using the same link you have now, you will receive latitud and longitude parameters grouped in location as a query string, something similar to:

pages/view_details?location%5Blatitude%5D=37.3505570824247&location%5Blongitude%5D=121.922104884669

And you can use them in your controller with params (as with any other parameter), for example:

latitude = params[:location][:latitude]
longitud = params[:location][:longitude]

Upvotes: 3

Related Questions