Ruby API - 接受参数并执行脚本 [英] Ruby API - Accept parameters and execute script

查看:25
本文介绍了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 方法,您可以在其中添加代码

 类 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.com/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆