主页

rails编写 api 接口,显示列表和详情数据

2023-10-31 09:25PM

参考:https://linlin.fun/blogs/1026

1.写一个 app/controllers/api/articles_controller.rb 文件

代码如下:

module Api
  class ArticlesController < ApplicationController

    def index
      articles = Article.select(:id, :title, :content, :created_at).order('created_at desc').page(params[:page] || 1).per(Article.count)
      count = articles.count rescue 0

      render json: {articles: articles, count: count}
    end

    def show
      article = Article.find(params[:id])
      render json: article
    end
  end
 end

2 配置路由:

在config/routes.rb 文件中增加下面的内容:

Rails.application.routes.draw do
   namespace :api do
    resources :articles, only: [:index, :show]
  end
end

3. 重启服务器

bundle exec rails server

返回>>

登录

请登录后再发表评论。

评论列表:

目前还没有人发表评论