如何在相同的Rails控制器操作中处理多个HTTP方法
答
你可以使用request.post来检查它是否是一个帖子吗?
if request.post?
#handle posts
else
#handle gets
end
为了让你的路由的工作:
resources :photos do
member do
get 'preview'
post 'preview'
end
end
答
这里的另一种方式。我包含了示例代码,用于响应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
答
只需要使用这个,只使用在相同的路线get和post
resources :articles do
member do
match 'action_do-you_want', via: [:get, :post]
end
end
答
你可以试试这个
match '/posts/multiple_action', to: 'posts#multiple_action', via: [:create, :patch, :get, :options]
对不起,挖掘它,但 - 是分享相同的路线两个动词莫名其妙地不好的做法? – 2014-05-04 03:33:15
我认为可以。或者它可以暗示你的设计有点差 – Ven 2014-05-15 13:42:42
@FelipeAlmeida海事组织这是不错的做法,如果使用时是有道理的。 – Dennis 2014-11-21 16:55:55