如何创建非字符串形式查询?解决查询中AND、OR及!=语法错误
Rails Active Record 查询语法修正方案
一、修正!=(不等于)的写法
你原来的:id != @product_id写法不符合Active Record哈希查询规则,以下是三种常用修正方式:
- 方法1:使用
where.not(Rails 5+推荐)
哈希格式下直接用where.not表达否定条件:Products.where.not(id: @product_id) - 方法2:数组条件写法
用数组形式明确写出SQL条件:Products.where(['id != ?', @product_id]) - 方法3:使用Arel表(复杂场景适用)
product_table = Products.arel_table Products.where(product_table[:id].not_eq(@product_id))
二、处理AND/OR逻辑的正确写法
原生SQL的AND/OR关键字不能直接嵌入哈希参数中,Active Record通过链式调用和or方法组合逻辑关系:
- AND逻辑:多个
where调用默认就是AND关系,无需额外写关键字。 - OR逻辑:需要用
or方法单独定义OR子条件,再和其他条件合并。
完整正确示例
# 先定义OR子条件 section_condition = Products.where(section_id: @section_id) type_condition = Products.where(type_id: @type_id) or_conditions = section_condition.or(type_condition) # 组合所有条件(默认AND关系) Products .where.not(id: @product_id) .where(init_time: ..Time.current) # 哈希格式表达init_time <= 当前时间 .merge(or_conditions)
混合数组与哈希的紧凑写法
如果需要更简洁的表达,也可以用数组条件处理OR部分,同时保留哈希的便利性:
Products.where.not(id: @product_id) .where(init_time: ..Time.current) .where('section_id = ? OR type_id = ?', @section_id, @type_id)
原写法报错原因
原写法混用了原生SQL关键字(AND/OR)和Active Record哈希查询语法,哈希参数仅支持键值对格式,无法识别裸写的SQL逻辑关键字,因此触发语法错误。
内容的提问来源于stack exchange,提问作者what l
相关产品推荐
相关产品推荐

