Jason Swett
Jason Swett

Reputation: 45074

Custom Rails routes

I have a model called appointment and I want to change the way the "new" page works. When the user clicks a certain hour slot on the calendar, I want the user to be taken to a page with a URL like this:

appointment/new/hour/10

This would take the user to the "new" page and the time for the appointment would be pre-populated at 10:00am.

I'm familiar with symfony routing but I find Rails routing a little bit confusing. Specifically, I don't know how to write my link_to function call in such a way that it will give me a URL like the one above.

I've R'd some of the FM but I didn't find a place that goes over the kind of thing I want to do. If someone could either explain how to do what I'm trying to do or simply point me to the pertinent documentation, that would be awesome.

Upvotes: 1

Views: 633

Answers (1)

idlefingers
idlefingers

Reputation: 32037

In your routes.rb you could create a route such as:

# Rails 3
match 'appointment/new/hour/:hour' => "appointments#new", :as => :new_appointment_with_time

# Rails 2
map.new_appointment_with_time 'appointment/new/hour/:hour', :controller => "appointments", :action => "new"

Then, you can use it in links:

link_to "10am", new_appointment_with_time_path(:hour => 10)

In the controller, you can retrieve the value and make your new appointment instance use it using params[:hour]:

@appointment = Appointment.new(:hour => params[:hour])

Upvotes: 5

Related Questions