Rails routes with query parameters

Not quite sure terminology, I did not find anything, but if someone can point me in the right direction, I will look again.

I have a controller called Logs. I would like to have a date, optionally part of the url. If the user does not indicate a date, they receive today. If a date is specified, then it is used. The urls would look like this:

localhost:3000/journals/7/ localhost:3000/journals/7/2013-01-22/ 

The first will be displayed today. The second will show content from January 22nd.

I started with this route:

 match '/journals/:id(/:date)', to: 'journals#show' 

And the corresponding controller

 class JournalsController < ApplicationController def show @user = User.find(params[:id]) if params[:date] @date = Date.parse(params[:date]) else @date = Date.today end end end 

And this works great, but how can I generate URLs with URL helpers? I tried this:

 <%= link_to "< Yesterday", journal_path(id: @user, date: @date.yesterday) %> 

It seems to actually work fine, but it gives me the url:

 localhost:3000/journals/7?date=2013-01-22 

instead:

 localhost:3000/journals/7/2013-01-22 

How can I save URLs sequentially constructed as / journalals /: id /: date

If there is a better approach, please let me know.

+7
source share
1 answer

Try this in the routes:

  resources :journals match '/journals/:id(/:date)' => 'journals#show', :constraints => { :date => /\d{4}-\d{2}-\d{2}/ }, :as => "journals_date" 
+4
source

All Articles