How do we identify parameters in a dynamic URL?

前端 未结 2 743
别那么骄傲
别那么骄傲 2021-01-16 12:11

We are building a Rails CMS where a blog or news listing can appear anywhere in the site tree. This means that any page knows their type based on a database field - eg: a p

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-16 12:38

    You can use route globbing and constraints to match a proper pattern.

    # Rails 2.x
    map.connect "*path/:year/:month", 
                 :constraints => {:year => /\d{4}/, :month => /0[1-9]|1[0-2]/ },
                 :controller => :pages, :action => :month_archive
    
    # Rails 3.x
    match "*path/:year/:month" => "pages#month_archive", 
                 :constraints => {:year => /\d{4}/, :month => /0[1-9]|1[0-2]/ }
    

    This will match /dogs/snoopy-news/2010/11 and pass :path => "dogs/snoopy-news", :year => "2010", :month => "11" in the params hash. It will match all routes that have a year and a month as the last two segments, regardless of how many segments come beforehand. And it will reject any route that doesn't match a proper year and month in the last two segments. What you do with the :path parameter is up to you in the controller.

提交回复
热议问题