Home > OS >  Rails ActiveRecord default values are overridden by default_scope
Rails ActiveRecord default values are overridden by default_scope

Time:05-09

DB Scheme

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

Model

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)

When I remove default_scope it works as expected.

Why is default_scope changing my default values. As far as I know default_scope is only used in queries and not in creation?

CodePudding user response:

The default_scope is also applied while creating/building a record. It is not applied while updating or deleting a record.

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

If you need a scope for query usage only, consider using the normal scope instead.

  • Related