假设我想在同一个URL上同时支持GET和POST方法。我如何在rails控制器动作中处理它?</ p>
答案 0 :(得分:65)
您可以使用request.post检查它是否是帖子?
if request.post?
#handle posts
else
#handle gets
end
让您的路线发挥作用:
resources :photos do
member do
get 'preview'
post 'preview'
end
end
答案 1 :(得分:6)
这是另一种方式。我包含了示例代码,用于响应不支持的方法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
答案 2 :(得分:4)
只需要使用它,只能在同一路径中使用get和post
resources :articles do
member do
match 'action_do-you_want', via: [:get, :post]
end
end
答案 3 :(得分:1)
你可以试试这个
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB"
version="3.0" toolsVersion="12118" systemVersion="16F73"
targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES"
useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
...
...
</document>
答案 4 :(得分:0)
我想说,最好的方法是在控制器中创建单独的动作并在路由中声明它们。
# config/routes.rb
...
get '/my_action' => 'my#my_action_get'
post '/my_action' => 'my#my_action_post'
...
# app/controllers/my_controller.rb
...
def my_action_get
# do stuff like listing smth
end
def my_action_post
# do other stuff
end
事实上,Rails默认使用相同的逻辑:index
和create
动作均由发送到相同路径(例如/articles
)的请求调用,但是,它们具有不同的请求方法:GET /articles
请求被重定向到index
操作并列出所有文章,而POST /articles
被重定向到create
操作并创建新文章。>
答案 5 :(得分:-1)
这对我有用:
在routers.db
strsplit(df,"")
[[1]]
[1] "\U00010603"
[[2]]
[1] "\U0001076b" "\U00010631" "\U0001076b"
[[3]]
[1] "\U00010631" "\U00010633"
[[4]]
[1] "\U0001061a" "\U00010655" "\U00010609" "\U00010631"
在posts_controler.rb
中Rails.application.routes.draw do
post '/posts', to: 'posts#create'
get '/posts', to: 'posts#list_all'
end
因此每个动作都引用一个不同的功能