[Feature][ActiveRecord] Add magic "not_" methods to model instances

Skip to first unread message

Matt Duszynski

Mar 5, 2020, 6:58:56 PM3/5/20
to Ruby on Rails: Core
Given an enum defined like so:
    enum some_field: { foo: 0, bar: 1, baz: 2 }

Rails will define positive and negative scopes for the possible values.
[21] pry(main)> SomeModel.foo.count
(2.2ms) SELECT COUNT(*) FROM "some_models" WHERE "
some_models"."some_field" = $1 [["some_field", 0]]
=> 5
[22] pry(main)> SomeModel.not_foo.count
(2.7ms) SELECT COUNT(*) FROM "
some_models" WHERE "some_models"."some_field" != $1 [["some_field", 0]]
=> 2

However, for an instance of the model, it only defines the positive predicate.
[23] pry(main)> SomeModel.last.foo?
=> false
[24] pry(main)>
NoMethodError: undefined method `not_foo?' for #<SomeModel:0x00007fc730786f28>
from /Users/mduszynski/.gem/ruby/2.6.5/gems/activemodel- `method_missing'

Would it make sense to have the negative predicate available on instances of the model? I think this could be added without breaking any existing applications, since methods with the same name would just be overriding this new magic one.
Reply all
Reply to author
0 new messages