Rails ActiveRecord 默认值被 default_scope 覆盖

Rails ActiveRecord default values are overridden by default_scope

数据库方案

create_table "user", force: :cascade do |t|
    t.string "name"
    t.boolean "active", default: false
end

型号

class User < ApplicationRecord
  default_scope { where(active: true) } # removing this line and it works
end

u = User.create!(name: "test")
# ^^^^ this creates a User with active: true

u.active? # true (should be false)

当我删除 default_scope 时,它按预期工作。

为什么 default_scope 更改我的默认值。 据我所知default_scope只用于查询,不用于创建?

default_scope 也适用于 creating/building 一条记录。更新或删除记录时不应用它。

参考:https://api.rubyonrails.org/classes/ActiveRecord/Scoping/Default/ClassMethods.html#method-i-default_scope

如果您只需要查询使用范围,请考虑改用普通范围。