【问题标题】:Rails 3. Checking for true values in SQLRails 3. 检查 SQL 中的真值
【发布时间】:2012-02-19 19:16:09
【问题描述】:

我需要检查exam 列的值是否为true。所以我设置了这个,但它不起作用......

@exam_shipments = Shipment.where("exam <> NULL AND exam <> 0 AND customer_id = ?", current_admin_user.customer_id)

# This one gives me error "SQLite3::SQLException: no such column: true:"
@exam_shipments = Shipment.where("exam = true AND customer_id = ?", current_admin_user.customer_id) 

@exam_shipments = Shipment.where("exam = 1 AND customer_id = ?", current_admin_user.customer_id)

【问题讨论】:

    标签: mysql ruby-on-rails ruby activerecord sqlite


    【解决方案1】:

    你真的应该坚持使用 AR 语法:

    @exam_shipments = Shipment.where(:exam => true, :customer_id => current_admin_user.customer_id)
    

    假设 :exam 是您的 Shipment 模型上的布尔字段。 ActiveRecord 负责将您的查询转换为给定数据库的正确语法。因此,您编写的内联 SQL 越少,您的代码就越与数据库无关且可移植。

    【讨论】:

    • 这可能是实际原因:一些数据库类型不提供实际的布尔数据类型。 ActiveRecord 通过各种方式模拟这些:对于 SQLite,单个字符是 tf,对于 MySQL,TINYINT 是 01,或者,对于 PostgreSQL 是布尔字段。
    【解决方案2】:

    为什么需要执行 SQL?

    做起来容易多了

    @exam_shipments = Shipment.find_by_id(current_admin_user.customer_id).exam?
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 1970-01-01
      相关资源
      最近更新 更多