2012-11-08 224 views
1

我正在嘗試重寫僅用於選項請求的資源路由。我需要這個來正確獲取跨域照片上傳請求。在Rails 2中覆蓋資源路由

的routes.rb

map.resources :photos 
map.connect '/photos', :controller => 'photos', 
    :action => 'options_stuff', :conditions => {:method => :options } 

photos_controller.rb

def options_stuff 
    puts "got to [email protected]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" 
    set_access_control_headers 
    head :ok 
    render :nothing => true, :status => 200 
end 


def set_access_control_headers 
    headers['Access-Control-Allow-Origin'] = '*' 
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS' 
    headers['Access-Control-Max-Age'] = '1000' 
    headers['Access-Control-Allow-Headers'] = '*,x-requested-with' 
    puts "headers are #{headers}" 
end 

但是它從來沒有得到到控制器我所需要的。我究竟做錯了什麼?

順便說一句,我下面講如何做到這一點下面的兩篇文章:http://www.codeodor.com/index.cfm/2011/7/26/Responding-to-the-OPTIONS-HTTP-method-request-in-Rails-Getting-around-the-Same-Origin-Policy/3387

https://gist.github.com/832700

更新 了很多痛苦的痛苦我報廢了控制器的想法後,雖然它沒有工作就像答案所示。相反,有人推薦過濾器前使用一個像這樣:

前集

before_filter :set_access_control_headers, :only => [:index] 


def set_access_control_headers 
    if !request.put? && !request.post? && !request.delete? && !request.get? 
    headers['Access-Control-Allow-Origin'] = '*' 
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS' 
    headers['Access-Control-Max-Age'] = '1000' 
    headers['Access-Control-Allow-Headers'] = '*,x-requested-with' 
    puts "headers are #{headers}" 

    render :nothing => true, :status => 200 
    return false 
    end 
end 
+0

行爲的名稱在您的路線中是錯誤的。它不應該是options_stuff? – Ashitaka

+0

謝謝修復。但那不是 –

+0

'在控制器中調試'printf'可能不是實現這一點的最佳方式,但至少你對此感到興奮。 – tadman

回答

3

我相信路由優先級從上到下,頂一個是最高優先級,下一個最低的。因此,請考慮切換您的路線,如下所示:

map.connect '/photos', :controller => 'photos', 
:action => 'options_stuff', :conditions => {:method => :options } 
map.resources :photos 
+1

第一個定義具有最高優先級。這可悲的是與最後一個堅持的Ruby相反。 – tadman

+0

是的,編輯清楚! –

+0

非常感謝你的工作。現在我得到了一個雙渲染,因爲資源也試圖渲染:OptionsController#options_stuff中的'ActionController :: DoubleRenderError' –