美文网首页
爱上 ruby on rails 二: 设计api及分页

爱上 ruby on rails 二: 设计api及分页

作者: RickyWu585 | 来源:发表于2022-08-20 15:14 被阅读0次

设计api

  1. 发送验证码
  • 资源:validation_codes
  • 动作:create(post)
  • 状态码:200 | 201 | 422(参数错误) | 429(too many request)
  1. 登录登出
  • 资源:session
  • 动作:create | destroy(delete)
  • 状态码:200 | 422
  1. 当前用户
  • 资源:me
  • 动作:show(get)
  1. 记账数据
  • 资源:items
  • 动作:create | update | show | index | destroy
    update 对应 PATCH,表示部分更新
    show 对应 GET /items/:id ,展示一条记账
    index 对应 GET /items?since=2022-01-01%before=2023-01-01
    destroy 对应 DELETE,表示删除,一般为软删除
  1. 标签
  • 资源:tags
  • 动作:ceate | update | show | index | destroy
  1. 打标签:记录标签和用户的关系,用中间缓存,不互相影响
  • 资源: taggings(动词的名词形式)
  • 动作: create | index | destroy

代码创建

  1. routes.rb: namespace代表前缀路径
Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      # /api/v1
      resources :validation_codes
    end
  end
end
  1. 运行bin/rails routes:自动生成一系列restful api,如果只想取其中某个api,则加 only 即可,想排除某个api,用exclude
Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      # /api/v1
      resources :validation_codes, only: [:create]
      resource :session, only: [:create, :destroy]
      resource :me, only: [:show]
      resources :items
      resources :tags
    end
  end
end
  1. bin/rails g model ... :示例bin/rails g model item user_id:integer amount:integer notes:text tags_id:integer happen_at:datetime
  2. 创建对应controller,这里以items为示例,执行命令:bin/rails g controller Api::V1::Items 会自动依据目录创建
  3. bin/rails db:migrate
  4. 尝试做一下分页:利用库kaminari或者pagy
  • 配置gemfilegem "kaminari"
  • bundle install:类似yarn,install可以省略
  • 实现:
class Api::V1::ItemsController < ApplicationController
  def index
    items = Item.page(params[:page]).per(params[:number])
    render json: { resources: items }
  end

  def create
    item = Item.new amount: 1
    if item.save
      render json: { resource: item }
    else
      render json: { errors: item.errors }
    end
  end
end

相关文章

网友评论

      本文标题:爱上 ruby on rails 二: 设计api及分页

      本文链接:https://www.haomeiwen.com/subject/aqfkbrtx.html