Rails Routes With Query Parameters

Not really sure the terminology involved, I didn't find anything searching but if someone can point me in the right direction I'll take another look.

I have a controller called Journals. I would like to have a date optionally part of the URL. If the user doesn't specify a date, they get today. If there is a date specified, then it is used. URLs would look like:

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

The first would show Today's contents. The second would show contents from the Jan 22.

I started with this route:

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

And a 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 fine, but how can I generate URLs using the url helpers? I tried this:

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

Which seems to actually work fine, but it gives me a url like this:

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

instead of:

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

How can I keep the URLs consistently built like /journals/:id/:date

If there is a better approach please let me know.


试试这条路线:

 resources :journals
 match '/journals/:id(/:date)' => 'journals#show', :constraints => { :date => /d{4}-d{2}-d{2}/ }, :as => "journals_date"
链接地址: http://www.djcxy.com/p/68890.html

上一篇: 对代码编译的方式非常迂腐

下一篇: Rails路由与查询参数