Ruby API – 接受参数并执行脚本

我创建了一个rails项目,其中包含一些我想作为API执行的代码。 我正在使用rails-api gem。

该文件位于app / controllers / api / stats.rb中。

我希望能够执行该脚本并通过访问此类链接返回json输出 – http://sampleapi.com/stats/?location=USA?state=Florida 。

我应该如何配置我的项目,以便当我访问该链接时它运行我的代码?

该文件应该被称为stats_controller.rb app/controllers/api/stats_controller.rb

您可以创建一个index方法,您可以在其中添加代码

  class API::StatsController < ApplicationController def index #your code here render json: your_result end end 

在文件config/routes.rb你应该添加

 get 'stats' => 'api/stats#index', as: 'stats' 

要访问url中的params,可以使用params[:location]params[:state]在索引方法中执行

以下是我对此的看法:

在app / controllers / api / stats_controller.rb中

 module Api class StatsController def index # your code implementation # you can also fetch/filter your query strings here params[:location] or params[:state] render json: result # dependent on if you have a view end end end 

在config / routes.rb中

 # the path option changes the path from `/api` to `/` so in this case instead of /api/stats you get /stats namespace :api, path: '/', defaults: { format: :json } do resources :stats, only: [:index] # or other actions that should be allowed here end 

让我知道这个是否奏效