ActiveRecord在相同布尔值的变化上返回不同的结果

时间:2018-01-29 15:49:36

标签: sql ruby-on-rails ruby activerecord

我一直在尝试根据特定查询检索一定数量的用户。我遇到的问题是,根据我使用false还是"false",我的搜索结果会有很大差异。以下是我的查询:

User.all
    .where.not(id:1)
    .where.not("lower(promo) = ?","promo")
    .where(created_at:7.months.ago..6.months.ago, auto_renew: false)

这将返回适合查询的三个用户的列表。但是当我运行以下内容时:

User.all
    .where.not(id:1)
    .where.not("lower(promo) = ?","promo")
    .where(created_at:7.months.ago..6.months.ago, auto_renew: "false")

这将返回一个不在原始列表中的用户。 auto_renew值应该是布尔值。为什么回报会有所不同,我该如何解决?

修改

根据请求,这是users的架构:

create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "",    null: false
    t.string   "encrypted_password",     default: "",    null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,     null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                             null: false
    t.datetime "updated_at",                             null: false
    t.string   "first_name"
    t.string   "last_name"
    t.boolean  "auto_renew",             default: true
  end

1 个答案:

答案 0 :(得分:4)

false != "false"。第一个是布尔,第二个是字符串

在99%的方案中,您应该使用false,而不是"false"

我不确定为什么这些查询会返回不同的结果集;它可能取决于您使用的rails /数据库引擎/版本。如果要查看两个命令之间的区别,请尝试运行:

User.where(.....).to_sql

如果由于某种原因您需要以编程方式将"false"转换为false,请参阅this answer