如何在Rails的ArticlesController中添加返回文章列表JSON的action
Rails返回文章列表JSON接口实现步骤
1. 编辑ArticlesController添加响应逻辑
推荐复用现有符合REST规范的index action,不影响原有HTML页面的访问,代码如下:
# app/controllers/articles_controller.rb class ArticlesController < ApplicationController # 原有其他action(show、new、edit等)保持不变 def index @articles = Article.all respond_to do |format| format.html # 保留原有的HTML响应逻辑 format.json { render json: @articles } end end # 如果你想要单独的自定义接口action,可以参考下面的写法,不需要额外写respond_to: # def json_list # @articles = Article.all # render json: @articles # end end
2. 配置路由(仅自定义action需要,复用index可跳过)
如果你用了上面的自定义json_list action,需要在路由文件中添加对应规则:
# config/routes.rb Rails.application.routes.draw do # 原有路由规则保持不变 # 方式1:直接写路由映射 get 'articles/json_list', to: 'articles#json_list' # 方式2:挂载到articles资源的集合路由下,更符合Rails规范 # resources :articles do # collection do # get :json_list # end # end end
3. 访问测试
- 复用
indexaction的场景:直接访问/articles.json即可获取JSON格式的文章列表 - 使用自定义action的场景:访问你配置的对应路由(比如
/articles/json_list)即可获取结果
可选优化
如果需要限定返回的字段,或者关联返回评论数据,可以修改render语句:
# 仅返回指定字段 render json: @articles, only: [:id, :title, :content, :created_at] # 排除不需要的字段 render json: @articles, except: [:updated_at] # 关联返回对应评论数据 render json: @articles, include: :comments
内容的提问来源于stack exchange,提问作者EGGo
相关产品推荐
相关产品推荐

