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

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

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

Matt Duszynski
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)>
SomeModel.last.not_foo?
NoMethodError: undefined method `not_foo?' for #<SomeModel:0x00007fc730786f28>
from /Users/mduszynski/.gem/ruby/2.6.5/gems/activemodel-6.0.2.1/lib/active_model/attribute_methods.rb:431:in `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.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-core/158997e8-82ef-4220-a784-dc25acbbd011%40googlegroups.com.