在Rails中覆盖资源路由2

时间:2012-11-08 19:05:01

标签: ruby-on-rails ruby http http-headers url-routing

我试图仅为选项请求覆盖资源的路由。我需要这样才能正确获取跨域照片上传请求。

的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 options@!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    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

1 个答案:

答案 0 :(得分:3)

我认为路线优先顺序从上到下,最高优先级最高,最低优先级最低。所以考虑改变这样的路线:

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