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

使用ancestry gem构建父分类时出现ActiveRecord::StatementInvalid错误

问题解决:ActiveRecord::StatementInvalid 语法错误

错误原因

你在Categories#new页面使用Category.where("id != #{@category.id}")时,@category是新创建的未保存记录,@category.id为nil,拼接后SQL变成WHERE (id != ),导致PostgreSQL语法错误。

解决方案

方法1:使用安全的ActiveRecord查询(推荐)

用where.not结合presence处理空值,当@category.id为空时自动忽略该条件:

<%= form.collection_select :parent_id, Category.where.not(id: @category.id.presence).order(:name), :id, :name, {include_blank: true} %>

方法2:区分新建和编辑场景

判断记录是否已保存(persisted?),新建时查询所有分类,编辑时排除自身:

<% categories = @category.persisted? ? Category.where.not(id: @category.id) : Category.all %>
<%= form.collection_select :parent_id, categories.order(:name), :id, :name, {include_blank: true} %>

注意事项

避免直接用字符串拼接SQL语句,不仅容易出现语法错误,还存在SQL注入风险,优先使用ActiveRecord提供的查询方法构建条件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 00:26:07