2014-01-29 27 views
0

我想要一个路由,其中​​'/'之后的所有字符串都是参数。在路由中使用整个路径作为参数

例如,如果网址是localhost:3000/posts/1/edit然后params[:path]应该等于

我一直试图做这样的事情

resource :item, path: '/:path', only: [:show, :update, :create, :destroy], constraints: { path: /.+/, format: :json } 

“的帖子/ 1 /编辑”但在这种情况下,如果我.json最后还包含了一个路径参数。我试过约束/.+\./另一个正则表达式,但它也不起作用。

我做错了什么?谢谢你!

+0

为什么你需要这在另一个PARAM怎么做呢?您已经可以在控制器中执行'request.env [“PATH_INFO”]'来获得相同的结果(尽管它会有开始的正斜杠,您可以轻松摆脱)。 – MrDanA

+0

@Pavel“Yo dawg”,我听说你喜欢regexing:路径,所以我改变了:路径为:_path,所以你可以有:路径,而你regexing:_path – SoAwesomeMan

回答

0

在你的控制器,与env['PATH_INFO']代替params[:path]

0
# SoAwesomeMan 
# Rails 3.2.13 
Awesome::Application.routes.draw do 
    resources :items, path: ':_path', _path: /[^\.]+/ 
    # http://localhost:3000/posts/1/edit.json?q=awesome 
    # => {"q"=>"awesome", "action"=>"index", "controller"=>"items", "_path"=>"posts/1/edit", "format"=>"json"} 
end 

class ItemsController < ApplicationController 
    before_filter :defaults 
    def defaults 
    case request.method 
    when 'GET' 
     case params[:_path] 
     when /new\/?$/i then new 
     when /edit\/?$/i then edit 
     when /^[^\/]+\/[^\/]+\/?$/ then show 
     else; index 
     end 
    when 'POST' then create 
    when 'PUT' then update 
    when 'DELETE' then destroy 
    else; raise(params.inspect) 
    end 
    end 

    def index 
    raise 'index' 
    end 

    def show 
    raise 'show' 
    end 

    def new 
    raise 'new' 
    end 

    def edit 
    raise 'edit' 
    end 

    def create 
    raise 'create' 
    end 

    def update 
    raise 'update' 
    end 

    def destroy 
    raise 'destroy' 
    end 
end