Rails将boolean 1解释为false

时间:2018-05-30 11:01:10

标签: ruby-on-rails boolean

我有一个恼人的问题:我想将用户标记为已删除,因此我创建了一个名为“已删除”的布尔数据库列,并将用户标记为已删除。现在,当我搜索它时:

ds = User.where(deleted: 1)
User Load (0.8ms)  SELECT  `users`.* FROM `users` WHERE `users`.`deleted` = 1 LIMIT 11
=> #<ActiveRecord::Relation [#<
   User id: 4, 
   vname: "Max", 
   nname: "Muster", 
   ...
   emailverified: true,
   deleted: false>]>

为什么Rails将1解释为false?一个应该是真的,如下面的搜索所示:

ds = User.where(deleted: true)
User Load (0.8ms)  SELECT  `users`.* FROM `users` WHERE `users`.`deleted` = 1 LIMIT 11
=> #<ActiveRecord::Relation [#<
   User id: 4, 
   vname: "Max", 
   nname: "Muster", 
   ...
   emailverified: true,
   deleted: false>]>

所以我搜索deleted = true并得到一条记录,其中deleted = false ???

我需要这个来进行我正在写的测试:

expect(user_after_deletion.deleted).to be true

但是user.deleted始终为false,即使数据库中存储了1。

使用“emailverified”字段,一切都按预期工作。列都是tinyint(1)。

我试图重命名该列,但仍然没有运气。

任何人都可以指出我正确的方向吗? 谢谢!

P.S .: user.rb

class User < ApplicationRecord

  attr_accessor :passwd_upd
  belongs_to :entitlement

  after_initialize :set_uid
  has_secure_password

  has_many :user_histories

 def self.automatic_deletion
    User.where("created_at > ?", (Time.now - 24.hours)).each do |u|
      u.deleted = true
      u.save(validate: false)
    end
  end

  def undelete
    self.deleted = false
  end
end

和相应的迁移。

class AddDeletedToUsers < ActiveRecord::Migration[5.1]
  def change
    add_column :users, :deleted, :boolean
  end
end

1 个答案:

答案 0 :(得分:0)

我&#34;解决了#34;它通过将Rails从5.1.4更新到5.2。

现在我明白了:

ds = User.where(deleted: true)
User Load (0.8ms)  SELECT  `users`.* FROM `users` WHERE `users`.`deleted` = 1 LIMIT 11
=> #<ActiveRecord::Relation [#<
   User id: 4, 
   vname: "Max", 
   nname: "Muster", 
   ...
   emailverified: true,
   deleted: true>]>

抱歉偷你的时间。