问题描述
限时送ChatGPT账号..我创建了一个 rails 项目,其中包含一些我想作为 API 执行的代码.我正在使用 rails-api gem.
该文件位于 app/controllers/api/stats.rb.
我希望能够通过访问这样的链接来执行该脚本并返回 json 输出 - http://sampleapi/stats/?location=USA?state=Florida.
我应该如何配置我的项目,以便在我访问该链接时它运行我的代码?
解决方案该文件应命名为 stats_controller.rb
app/controllers/api/stats_controller.rb
>
您可以创建一个 index
方法,您可以在其中添加代码
类 API::StatsController 应用控制器定义索引#你的代码在这里渲染 json:your_result结尾结尾
在文件 config/routes.rb
中你应该添加
get 'stats' =>'api/stats#index',如:'stats'
要访问 url 中的参数,您可以在 index 方法中使用 params[:location]
,params[:state]
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.
The file is located in app/controllers/api/stats.rb.
I would like to be able to execute that script and return json output by visiting a link such as this - http://sampleapi/stats/?location=USA?state=Florida.
How should I configure my project so that when I visit that link it runs my code?
解决方案the file should be called stats_controller.rb
app/controllers/api/stats_controller.rb
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
in the file config/routes.rb
you should add
get 'stats' => 'api/stats#index', as: 'stats'
To access the params in the url you can do it in your index method with params[:location]
,params[:state]
这篇关于Ruby API - 接受参数并执行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论