gpt4 book ai didi

ruby-on-rails - 如何为现有的 Rails 应用构建版本 API?

转载 作者:行者123 更新时间:2023-12-04 07:29:04 24 4
gpt4 key购买 nike

如何为现有的 Rails 应用构建版本 API?我已经构建了一个简单的应用程序,具有用户和公司的关系

Company has_many users

User belongs_to company

我如何为这个应用构建一个版本控制 api

最佳答案

API 的目录结构

在这里,ApiController 是 ApplicationController 的子类,并充当所有其他 API Controller 的父类。

app/controllers/
.
|-- api
| `-- v1
| |-- api_controller.rb
| |-- users_controller.rb
|-- companies_controller.rb
|-- application_controller.rb

这是 Controller 的样子:

app/controllers/api/v1/api_controller.rb

module Api::V1
class ApiController < ApplicationController
#API stuff here
end
end

app/controllers/api/v1/users_controller.rb

module Api::V1
class UsersController < ApiController

# POST /v1/users
def create
your code goes here
end

end
end

API 路由

routes.rb

namespace :api, defaults: {format: :json} do
namespace :v1 do
resources :users
end
end

用户索引操作的 API URL,仅作为示例

http://localhost:3000/api/v1/users.json 

关于ruby-on-rails - 如何为现有的 Rails 应用构建版本 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36569914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com