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

使用Rails GraphQL+Vue Apollo创建分类后查询无法获取新分类

问题描述

我使用 Rails + GraphQL、Vue + Apollo 技术栈开发,已经成功创建了 Category 记录,但调用查询接口获取所有分类时,无法返回刚创建的新分类。

前端查询代码

async getCategories() {
  this.loading = true;
  try {
    const response = await this.$apollo.query({
      query: gql`
        query Categories{
          categories {
            id
            name
          }
        }
      `,
    });
    // this.$store.commit('updateCategoriesState', {
    //   categories: response.data.categories,
    // });
    console.log(response.data.categories)
  } catch (error) {
    // turn this on for debugging
    // console.log(error)

  } finally { 
    this.loading = false;
  }
},

后端 GraphQL Query 代码

# Category query field
field :categories, [Types::CategoryType], null: false

# Category resolver
def categories
  categories = Category.all
  categories
end

排查与解决方法

1. 先确认新分类是否真的写入数据库

直接登录数据库或者在 Rails Console 执行 Category.last,看看新创建的分类是否存在。如果数据库里没有这条记录,问题出在创建分类的 mutation 逻辑,比如事务未提交、参数验证失败但没抛出错误,先排查创建环节。

2. 检查 Apollo 客户端缓存

Apollo 默认会缓存查询结果,创建分类后如果没更新缓存,再次调用相同查询会直接返回旧数据:

  • 方案一:在创建分类的 mutation 中添加 refetchQueries,自动刷新分类列表:
    await this.$apollo.mutate({
      mutation: CREATE_CATEGORY_MUTATION,
      variables: { name: "新分类" },
      refetchQueries: [{ query: gql`query Categories{ categories { id name } }` }]
    })
    
  • 方案二:查询时禁用缓存(仅临时调试用):
    const response = await this.$apollo.query({
      query: gql`...`,
      fetchPolicy: 'no-cache' // 强制从服务器拉取最新数据
    })
    

3. 检查后端 resolver 隐藏过滤逻辑

确认 Category.all 没有被全局 scope 篡改:

  • 比如项目中用了软删除,默认 scope 是 default_scope { where(deleted_at: nil) },如果创建分类时误设了 deleted_at,就会被过滤;
  • 在 resolver 加日志验证返回数据:
    def categories
      categories = Category.all
      Rails.logger.info "返回的分类ID列表: #{categories.pluck(:id)}"
      categories
    end
    
    查看 Rails 日志,确认新分类的 ID 是否在返回列表里。

4. 确认查询调用时机

确保 getCategories 是在创建分类的 mutation 完成后才执行的,如果是在 mutation 未结束时就调用查询,自然拿不到新数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:55:00