红宝石API - 接受参数和执行脚本 [英] Ruby API - Accept parameters and execute script
问题描述
我已经创建了具有一定code,我想执行作为API Rails项目。我现在用的导轨-API的宝石。
I have created a rails project that has some code that I would like to execute as an API. I am using the rails-api gem.
该文件位于应用程序/控制器/ API / stats.rb。
The file is located in app/controllers/api/stats.rb.
我希望能够执行该脚本,并通过访问链接像这样的返回JSON输出 - 的 http://sampleapi.com/stats/?location=USA?state=Florida 。
I would like to be able to execute that script and return json output by visiting a link such as this - http://sampleapi.com/stats/?location=USA?state=Florida.
我应该如何配置我的项目,所以,当我访问该链接,它运行我的code?
How should I configure my project so that when I visit that link it runs my code?
推荐答案
该文件应该被称为 stats_controller.rb
应用程序/控制器/ API / stats_controller.rb
您可以创建一个首页
方法,您可以添加您的code
you can create an index
method where you can add your code
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'
要访问PARAMS中的网址,你可以用 PARAMS做它在你的索引方法[:位置]
, PARAMS [:状态]
To access the params in the url you can do it in your index method with params[:location]
,params[:state]
这篇关于红宝石API - 接受参数和执行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!