【问题标题】:Ruby API - Accept parameters and execute scriptRuby API - 接受参数并执行脚本
【发布时间】:2016-08-03 17:53:52
【问题描述】:

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

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

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

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

【问题讨论】:

  • 我认为你的意思是http://sampleapi.com/stats/?location=USA&state=Florida的URL。 URL 查询字符串只允许一个“?”它将查询字符串与路径分开。
  • 感谢您的提示

标签: ruby-on-rails ruby api rails-api


【解决方案1】:

该文件应称为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 中的参数,您可以在 index 方法中使用 params[:location]params[:state] 进行操作

【讨论】:

  • 我不断收到此错误,我不知道如何解决它。 Unable to autoload constant API::StatsController, expected /home/ubuntu/workspace/app/controllers/api/stats_controller.rb to define it
  • 你的控制器名称应该是Api::StatsController
  • 好的,非常感谢!这行得通,但你必须拥有全部大写的 API。
【解决方案2】:

这是我的想法:

在 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

让我知道这是否有效

【讨论】:

    猜你喜欢
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 2023-03-11
    • 2015-08-29
    • 2013-06-19
    • 1970-01-01
    • 2013-06-07
    相关资源
    最近更新 更多