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

Rails通过JS请求更新关联多值失败,嵌套属性更新不生效求助

问题原因

  1. 前端update请求传递的post_items_attributes没有携带对应post_item记录的id,Rails的嵌套属性更新逻辑必须通过id识别需要更新的关联记录,缺少id时不会触发现有记录更新。
  2. 控制器update方法调用错误:你直接调用关联集合post.post_items.update,但该方法接收的是单个属性哈希用于批量更新所有关联项,无法识别post_items_attributes嵌套结构,嵌套属性是父模型Post的功能,需要调用父模型的update方法触发处理逻辑。
  3. 控制器update方法没有设置响应,默认返回204无内容,无法排查是否更新失败。

修改方案

1. 调整JavaScript侧update代码

map的时候加入每条待更新post_item的id:

update (context) {
  const list = context.state.todos.list
  const bookId = context.state.book.selectedBook.id
  const content =
  list.map((item) => {
    return {
      id: item.id, // 新增:携带post_item的id
      content: item.content,
      status: false
    }
  })
  this.$axios.$patch(url.POST_API + 'posts/' + bookId, {
    post: {
      post_items_attributes: content
    }
  })
}

如果你的业务场景是全量替换当前post的所有post_item(删除旧记录、新增新的列表),则可以不需要传id,直接在控制器update里先删除所有关联的post_item再新建,更推荐带id的更新方案。

2. 调整Rails控制器update代码

def update
  post = Post.find(params[:id])
  if post.update(content_params)
    render json: "OK", status: 200
  else
    render json: { errors: post.errors.full_messages }, status: 422
  end
end

修改后如果更新失败会返回具体错误信息,方便前端排查问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:27:00