You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails中基于现有数据库创建指定REST API接口

在Rails 7中实现最小化REST接口(GET/修改用户卡片)

针对你的需求,以下是基于现有数据库结构实现GET /users/:userId/cards接口及卡片修改功能的步骤,完全适配你用rails new stresstest --api --minimal -d=postgresql创建的项目:

1. 创建模型(映射现有数据库表)

Rails通过模型关联数据库表,你不需要生成新的迁移文件,直接创建以下三个模型:

User模型 (app/models/user.rb)

class User < ApplicationRecord
  has_many :has_permissions
  has_many :cards, through: :has_permissions
end

Card模型 (app/models/card.rb)

class Card < ApplicationRecord
  has_many :has_permissions
  has_many :users, through: :has_permissions
end

HasPermission模型 (app/models/has_permission.rb)

如果你的数据库表名是HasPermissions(首字母大写),需要手动指定表名,否则Rails会默认查找小写复数的has_permissions表:

class HasPermission < ApplicationRecord
  self.table_name = 'HasPermissions' # 和数据库表名一致,无需的话可删除此行
  belongs_to :user
  belongs_to :card
end

2. 配置数据库连接

修改config/database.yml,填入你现有PostgreSQL数据库的信息:

default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  host: localhost # 你的数据库主机地址
  username: 你的数据库用户名
  password: 你的数据库密码

development:
  <<: *default
  database: 你的现有数据库名称

test:
  <<: *default
  database: 你的现有数据库名称_test

production:
  <<: *default
  database: 你的现有数据库名称_production
  username: stresstest
  password: <%= ENV["STRESSTEST_DATABASE_PASSWORD"] %>

3. 设置路由

修改config/routes.rb,添加嵌套路由,只保留需要的接口动作:

Rails.application.routes.draw do
  # 仅定义所需的用户-卡片嵌套路由
  resources :users, only: [] do
    resources :cards, only: [:index, :update]
  end
end

这会生成两个核心接口:

  • GET /users/:user_id/cards:获取指定用户的所有卡片
  • PUT/PATCH /users/:user_id/cards/:id:修改指定用户有权限的卡片

4. 创建Cards控制器

运行命令生成控制器(跳过不必要的资源文件):

rails generate controller Cards --skip-assets --skip-helper --skip-template-engine

然后修改app/controllers/cards_controller.rb,实现接口逻辑:

class CardsController < ApplicationController
  # GET /users/:user_id/cards
  def index
    user = User.find(params[:user_id])
    # 直接通过关联获取用户有权限的所有卡片
    @cards = user.cards
    render json: @cards
  end

  # PUT/PATCH /users/:user_id/cards/:id
  def update
    user = User.find(params[:user_id])
    # 仅允许修改用户有权限的卡片
    card = user.cards.find(params[:id])
    if card.update(card_params)
      render json: card
    else
      render json: card.errors, status: :unprocessable_entity
    end
  end

  private

  # 限制可修改的字段(仅允许修改text)
  def card_params
    params.require(:card).permit(:text)
  end
end

5. 测试接口

启动Rails服务器:

rails server

用Postman或curl测试:

  • 获取卡片:发送GET http://localhost:3000/users/1/cards(把1换成实际存在的user_id),会返回该用户关联的所有卡片JSON。
  • 修改卡片:发送PUT http://localhost:3000/users/1/cards/2,请求体传{"card": {"text": "更新后的卡片内容"}},只有当用户有权限操作该卡片时才会成功修改。

关键说明

  • 因为用了--api模式,控制器默认已经适配API场景,无需额外配置视图或模板。
  • 关联关系has_many :through会自动通过HasPermissions表查询用户和卡片的关联,无需手动编写SQL。
  • user.cards.find(params[:id])会自动验证用户是否有权限操作该卡片,不存在或无权限会返回404状态码。

内容的提问来源于stack exchange,提问作者Nuubles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:45:11