代码之家  ›  专栏  ›  技术社区  ›  Jay

Rails:通过检测参数映射冲突的路由

  •  0
  • Jay  · 技术社区  · 16 年前

    嘿!我试图在Rails应用程序中设置路由,以便根据传递的参数类型,Rails将请求发送到不同的操作。

    我有 courses 有属性的 state 它是一个带有两个字母的国家缩写的字符串。当用户访问时 /courses/1 ,我希望Rails显示 show 行动在 课程 控制器(并将参数传递为 :id )当用户访问时 /courses/CO 不过,我希望Rails显示 index 动作并将参数传递为 :state .

    所以 课程/ 1 相当于

    :controller => 'courses', :action => 'show', :id => '1'
    

    和 课程/ CO 相当于

    :controller => 'courses', :action => 'index', :state => 'CO'
    

    我尝试过:

    map.resources :courses, :except => { :index, :show }
    map.connect 'courses/:state', :controller => 'courses', :action => 'index', :state => /[A-Z]{2}/
    map.connect 'courses/:id',    :controller => 'courses', :action => 'show', :id => /[0-9]+/
    

    但它坏了(Rails服务器甚至不会启动)。我通常不会用Routes做这种事情,所以我不知道该怎么做。谢谢!

    编辑:修正了一个打字错误,谢谢JC。

    当前解决方案如下:

    map.resources :courses, :except => [ :index, :show ]
      map.courses  '/courses',        :controller => 'courses', :action => 'index', :state => 'AL', :method => :get
      map.courses  '/courses/:state', :controller => 'courses', :action => 'index', :requirements => { :state => /[A-Z]{2}/ }, :method => :get
      map.course   '/courses/:id',    :controller => 'courses', :action => 'show',  :requirements => { :id => /[0-9]+/      }, :method => :get
    
    2 回复  |  直到 16 年前
        1
  •  3
  •   Joshua Cheek    16 年前

    这是可行的,但是你需要去编辑你的所有链接到索引上,这样说 courses_path('AA') and you won't be able to use some of the nice helpers, like form_for, which assume you are following the convention that #create is simply #index with a POST request. (Get comfortable with form_tag)

    ActionController::Routing::Routes.draw do |map|
      map.resources :courses, :except => [ :index, :show ]
      map.courses  '/courses/:state', :controller => 'courses', :action => 'index', :requirements => { :state => /[A-Z]{2}/ } , :method => :get
      map.course   '/courses/:id',    :controller => 'courses', :action => 'show',  :requirements => { :id => /[0-9]+/      } , :method => :get
    end
    

    不过,它将保持您的路线名称不变。

    (顺便说一下,您的/co与您的regex不匹配,后者需要大写字符)


    有趣的是:我们真的需要一个路由器的抽象吗? http://blog.peepcode.com/tutorials/2010/rethinking-rails-3-routes

        2
  •  0
  •   flitzwald    16 年前

    I'm afraid this won't work since the structure that maps paths to controllers and actions is setup on start of the rails application, parameter handling happens at request time.

    您可以做的是将CuthScript控制器的显示动作中的ID参数与有效状态列表匹配,然后重定向或呈现不同的操作。

    希望这有帮助。