2011-04-07 79 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] 
相關問題