Rails API 构建入门指南 | 作者:Koray Ozkal | 发布于 The Startup

作者:API传播员 · 2025-12-05 · 阅读时间:5分钟
本指南从零开始构建Rails API应用程序,涵盖创建API模式、配置CORS、规划数据模型、生成控制器和路由等步骤,帮助开发者快速上手Rails API开发,并集成前端框架。

Rails API 构建入门指南

在本指南中,我们将从零开始构建一个基于 Rails 的 API 应用程序。本文将逐步带您完成创建、配置和测试 Rails API 的过程,帮助您快速上手。


第一步:创建一个新的 Rails 应用程序作为 API

首先,我们需要创建一个新的 Rails 应用程序,并将其设置为 API 模式。在终端中运行以下命令:

rails new  --api

这里的 --api 标志用于指定我们创建的是一个 API 应用程序。与传统的 Rails 应用不同,API 模式下会移除许多不必要的默认特性和中间件,例如视图层。控制器将继承自 ActionController::API 而非 ActionController::Base

例如,我们可以创建一个名为 comics_geek_backend 的应用程序:

rails new comics_geek_backend --api

如果您计划将应用部署到 Heroku 等环境,建议使用 PostgreSQL 作为数据库。可以通过以下命令创建应用:

rails new comics_geek_backend --database=postgresql --api

第二步:配置 CORS 以允许前端请求

接下来,我们需要配置 CORS(跨域资源共享),以便前端能够向我们的 API 发出请求。首先,运行以下命令安装依赖:

bundle install

然后,打开 config/initializers/cors.rb 文件,取消注释以下代码并修改 origins 的值为 '*',以允许所有主机访问:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

第三步:规划模型

在构建 API 前,我们需要规划数据模型。以漫画书应用为例,我们将创建以下两个模型:

  1. Comicbook 模型:

    • 属性:title(标题)、number(编号)、artist(艺术家)、writer(作者)、image_url(封面图片)、description(描述)。
    • 关系:属于 Publisher
  2. Publisher 模型:

    • 属性:name(名称)。
    • 关系:拥有多个 Comicbook

第四步:生成模型并创建数据库

使用 Rails 生成器创建模型。在终端中运行以下命令:

rails g model Publisher name --no-test-framework
rails g model Comicbook title description image_url publisher_id:integer number:integer artist writer --no-test-framework

然后运行以下命令创建数据库并迁移:

rails db:create && rails db:migrate

第五步:创建种子数据并测试关联

接下来,我们在 db/seeds.rb 文件中添加一些初始数据:

marvel = Publisher.create(name: "Marvel Comics")
dc = Publisher.create(name: "DC Comics")
image = Publisher.create(name: "Image Comics")

Comicbook.create(title: "Amazing Spider-man", number: 1, description: "Peter Parker tries to continue a show biz career as Spider-Man, yet J. Jonah Jameson's editorials slamming him as a menace makes it hard to find work.", image_url: "https://images-na.ssl-images-amazon.com/images/S/cmx-images-prod/Item/562/DIG000136._SX360_CLs%7C360,508%7Ccu/cmx-cu-sash-lg.png%7C0,0,361,509%20208,356,152,152_QL80_TTD_.jpg", artist: "Steve Ditko", writer: "Stan Lee", publisher_id: marvel.id)Comicbook.create(title: "Flash Rebirth", number: 1, description: "Geoff Johns and Ethan Van Sciver, the writer/artist team behind the blockbuster GREEN LANTERN: REBIRTH and THE SINESTRO CORPS WAR, create an explosive, jaw-dropping epic that reintroduces Barry Allen as The Flash in this volume collecting the fast-paced 6-issue miniseries.", image_url: "https://images-na.ssl-images-amazon.com/images/S/cmx-images-prod/Item/48457/DIG010147_1._SX360_QL80_TTD_.jpg", artist: "Ethan Van Sciver", writer: "Geoff Johns", publisher_id: dc.id)Comicbook.create(title: "Darkness", number: 1, description: "Introducing mafia hitman Jackie Estacado and the ancient power of the Darkness!", image_url: "https://images-na.ssl-images-amazon.com/images/S/cmx-images-prod/Item/1166/ICO000034._SX312_CLs%7C312,473%7Ccu/cmx-cu-sash-lg.png%7C0,0,313,474%20160,321,152,152_QL80_TTD_.jpg", artist: "Mark Silvestri", writer: "Mark Silvestri", publisher_id: image.id)

运行以下命令填充数据库:

rails db:seed

最后,通过 Rails 控制台测试关联:

rails c
spiderman = Comicbook.first
puts spiderman.title
puts spiderman.artist

第六步:生成控制器

创建控制器以处理 API 请求。在终端中运行以下命令:

rails g controller Comicbooks
rails g controller Publishers

例如,在 app/controllers/comicbooks_controller.rb 文件中添加一个 index 操作:

class ComicbooksController < ApplicationController
  def index
    comicbooks = Comicbook.all
    render json: comicbooks
  end
end

第七步:创建路由

打开 config/routes.rb 文件,为 index 操作添加路由:

Rails.application.routes.draw do
  resources :comicbooks, only: [:index]
end

第八步:测试 API

启动 Rails 服务器:

rails s

在浏览器中访问 http://localhost:3000/comicbooks,您将看到返回的 JSON 数据。至此,我们的 Rails API 已成功构建!


通过以上步骤,您已经完成了一个简单的 Rails API 应用程序的构建。接下来,您可以根据需求继续扩展功能,例如添加更多模型、控制器和路由,或者集成前端框架。

原文链接: https://medium.com/swlh/beginners-guide-to-building-a-rails-api-7b22aa7ec2fb