使用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
相关产品推荐
相关产品推荐

