Gotjosh
Gotjosh

Reputation: 1049

Rails way of constructing & redirecting to an url with post parameters of a form

I would like to do that's the best way of actually accomplishing the following on Rails.

I have a "Booking Form" with 5 fields (Property, Amount of Children, Amount of Adults and 2 Dates - Departure and Arrival) based on these fields, I need to construct an URL and redirect the user to this url. Now, I have 2 questions.

1) How i catch the POST parameters in the controller, because I'm mapping the form to an action like this:

<% form_tag(:action => "booking") do %> 

and routing it to a controller action like this: (Pages Controller, Booking Action)

match 'pages/booking' => 'pages#booking' 

2) Is this the Rails way of actually accomplishing such thing? I did it this way in PHP in the past, but now I have the need of actually doing it in Rails, could you Rails Gurus inspire me ?

Upvotes: 1

Views: 446

Answers (2)

Andy Lindeman
Andy Lindeman

Reputation: 12165

To access parameters in the controller, even ones submitted in a POST body, use the params hash. Eg: params[:form_field]

To redirect to another URL using a controller, use redirect_to. You can certainly use the values in params to construct a URL and pass it to redirect_to.

Upvotes: 3

tadman
tadman

Reputation: 211570

If you're using resourceful routes, which is the best way to go about such things, you would route things through the traditional approach:

resources :bookings

Then you'd post the form to bookings_path and it would all work out, as that's BookingsController#create. It's always better to have a strong correlation between model and controller where possible.

The resources definition in routes.rb helps you by creating all the default RESTful actions which you can build off of. If you really need a custom route, you can always rename it using the :as option, or route it independently.

If you go about creating your own arbitrary routes, such as /pages/booking you're going to create quite a mess that someone else will have to maintain. Quite often that someone else is you in the future.

Upvotes: 0

Related Questions