2014-01-29 67 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 
相關問題