2

我正在尝试post在控制器中定义自定义操作,但我有一些问题。

这是我的控制器:

module Api
  module V1
    class ExamplesController < ApplicationController
      def create_a
        ...
      end

      def create_b
        ...
      end
    end
  end
end

我希望两个动作/方法都是post动作。这是我的路线文件中的内容:

namespace :api do
  namespace :v1 do
    match 'examples/create_a', :controller => 'examples', :action => 'create_a'
    match 'examples/create_b', :controller => 'examples', :action => 'create_b'
  end
end

我可以通过 t 请求达到这两种方法ge,但我想基于 http 触发它们post。此外,如果我通过rake routes它检查并不会告诉我它是否是 GET、PUT、POST 等方法。它只是空白。我如何告诉路线它应该是一种post方法?

浏览器中的post请求在我的方法中看起来如何?

url: http://localhost:3000/api/v1/examples/create_a.json/create_a
header: Content-Type: application/x-www-form-urlencoded
data: paramA=45&paramB&paramC

这是post对我的控制器操作执行的正确 URL 模式create_a吗?

4

2 回答 2

2

添加 :via => :post 应该可以解决问题。

namespace :api do
  namespace :v1 do
    match 'examples/create_a', :controller => 'examples', :action => 'create_a', :via => :post
    match 'examples/create_b', :controller => 'examples', :action => 'create_b', :via => :post
  end
end

更多信息请访问http://guides.rubyonrails.org/routing.html

于 2012-09-13T13:42:54.853 回答
2

通常,match当您想要将某种逻辑名称映射到 RESTful 路由和/或为 RESTful 路由创建别名时使用。你正在做的事情match很好(从某种意义上说它会起作用),但你只是错过了一件小事(我稍后会告诉你)。

match首先,让我们看一下为路由创建别名的典型用法:

match "profile" => "users#show"

此路由允许您使用/profileto showa的应用程序路径user而不是 path /users/:id

由于您的代码没有将一个名称映射到另一个名称,因此您不需要match规则。您的使用match将不必要的重复添加到您的代码中,并且match在您提供的情况下使用比必要的更冗长。这是一个示例,说明如何在没有 match的情况下编写 API 路由,并指定它们只能通过以下方式访问post

namespace :api do
  namespace :v1 do
    post "examples/create_a"
    post "examples/create_b"
  end
end

这是一个带有 的示例match,添加:via参数(这是您的代码示例中缺少的)以指定 HTTP 动词:

namespace :api do
  namespace :v1 do
    match 'examples/create_a' => "examples#create_a", :via => :post
    match 'examples/create_b' => "examples#create_b", :via => :post
  end  #           ^ ---- DUPLICATION ---- ^
end

注意这里的代码重复。由于您没有将一个路径名映射到另一个路径名,因此与非版本相比,您输入了两次同名路径。match

您还会注意到,与原始示例代码相比,我去掉了:controllerandaction参数,因为 Rails 会在您使用表单时自动推断:

"[controller]/[action]" => "[controller]#[action]"
于 2012-09-13T13:48:06.590 回答