2011-04-07 82 views

回答

60

你可以使用request.post来检查它是否是一个帖子吗?

if request.post? 
    #handle posts 
else 
    #handle gets 
end 

为了让你的路由的工作:

resources :photos do 
    member do 
    get 'preview' 
    post 'preview' 
    end 
end 
+1

对不起,挖掘它,但 - 是分享相同的路线两个动词莫名其妙地不好的做法? – 2014-05-04 03:33:15

+1

我认为可以。或者它可以暗示你的设计有点差 – Ven 2014-05-15 13:42:42

+0

@FelipeAlmeida海事组织这是不错的做法,如果使用时是有道理的。 – Dennis 2014-11-21 16:55:55

5

这里的另一种方式。我包含了示例代码,用于响应405不支持的方法,并显示在URL上使用OPTIONS方法时支持的方法。

app/controllers/foo/bar_controller.rb

before_action :verify_request_type 

def my_action 
    case request.method_symbol 
    when :get 
    ... 
    when :post 
    ... 
    when :patch 
    ... 
    when :options 
    # Header will contain a comma-separated list of methods that are supported for the resource. 
    headers['Access-Control-Allow-Methods'] = allowed_methods.map { |sym| sym.to_s.upcase }.join(', ') 
    head :ok 
    end 
end 

private 

def verify_request_type 
    unless allowed_methods.include?(request.method_symbol) 
    head :method_not_allowed # 405 
    end 
end 

def allowed_methods 
    %i(get post patch options) 
end 

config/routes.rb

match '/foo/bar', to: 'foo/bar#my_action', via: :all 
+1

这些路线部分帮助我配置了我想要的东西。谢谢! – mjnissim 2015-06-29 08:07:43

2

只需要使用这个,只使用在相同的路线get和post

resources :articles do 
    member do 
    match 'action_do-you_want', via: [:get, :post] 
    end 
end 
0

你可以试试这个

match '/posts/multiple_action', to: 'posts#multiple_action', via: [:create, :patch, :get, :options] 
相关问题