【问题标题】:Rails where clause returns nil when asking for all records with boolean set to falseRails where 子句在请求所有布尔值设置为 false 的记录时返回 nil
【发布时间】:2014-08-12 04:43:44
【问题描述】:

我有一个具有布尔属性的用户模型 :sourced

我想写下面的代码,但我得到一个空数组

User.where(sourced: false)
#   User Load (2.0ms)  SELECT "users".* FROM "users" WHERE "users"."sourced" = 'f' ORDER BY  users.id DESC
# => [] 

但是,情况并非如此,因为实际上有些记录的来源设置为假。

即,当我运行时

  User.first.sourced #=> false 

在我的 schema.rb 文件中,它显示 'sourced' 列的默认值为 false

  create_table "users", force: true do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "password_digest"
    t.string   "remember_token"
    t.boolean  "admin",                              default: false
    t.string   "password_reset_token"
    t.datetime "password_reset_sent_at"
    t.text     "admin_note",             limit: 800
    t.integer  "applications_count"
    t.string   "admin_link"
    t.boolean  "sourced",                            default: false
    t.boolean  "told_admin"
  end

这里发生了什么?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    这是因为您在迁移中没有设置默认值 false ,因此它会将其保存为 nil ,而您不需要。使用鸭子输入 nil == false 所以在红宝石级别上它是错误的。

    虽然您可以查询 false 和 nil……但这有点麻烦。只需在数据库中设置一个默认值。

    你可以通过迁移来解决这个问题

    def up
      #change column
      change_column :users, :sourced, :boolean, default: false
    
    
      # reload schema https://stackoverflow.com/a/8935621/793330
      User.reset_column_information
    
      # update the nils 
      User.find_each(&:save) 
    end 
    

    请务必记住为数据库中的布尔值设置默认值。这将为您在未来节省大量的挫败感,并且通过始终在数据库级别设置默认值来帮助验证。

    如果您使用的是 SQLite?也许它的not typecasting properly 可以吗?

    User.where(sourced: 0) 
    

    【讨论】:

    • 嘿工程师戴夫,这是古怪的事情,sourced 已经将默认值设置为 false。答案已更新以反映这一点。你认为会发生什么?
    • 你在使用 SQLite 吗? stackoverflow.com/a/6013177/793330 也许它的类型转换不正确 sourced: 0 有效吗?
    • 啊,是的!好吧,这很古怪:|。感谢!
    • 如果是这样,您可能想要使用 Postgres。它增加了一点学习曲线,但它建立了更好的技能组合 IMO。 :) 此外,Docker 在简化设置方面还有很长的路要走,并给你一个丢弃的数据库,但是你也有更多的东西要学习,但如果设置 Postgres 太令人生畏,这是一个选择。 :)
    猜你喜欢
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 2016-06-24
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多