-
Notifications
You must be signed in to change notification settings - Fork 92
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Array of enums #52
Comments
Hi, @23tux! Right now class User < ApplicationRecord
...
validates :roles, array: { inclusion: { in: ROLES }
end |
I guess that |
@DmitryTsepelev Consider this example, maybe it's clearer this way:
My user has a configuration with an enum of |
Aha, in this case having the built-in inclusion validator for arrays makes sense to me! |
@FunkyloverOne you are right, enumerize has built in support for Arrays when you serialize them or use mongodb. I still have to find out if it works with json array columns though. But because we already have the store_model gem in our Gemfile, adding another dependency for this simple use case isn't something I'm very happy about |
@DmitryTsepelev How would you implement this? If you can give me a push in the right direction, I'm happy to try for a PR. |
@23tux This is what should be done to make it work:
As a result, it will be possible to add a validation to the class Configuration
include StoreModel::Model
ROLES = %i[admin user reporter]
enum :role, ROLES, default: :user
validates :roles, array: { inclusion: { in: ROLES }
end
class User < ApplicationRecord
attribute :configuration, Configuration.to_type
end Bonus point: it might be helpful to have a shortcut for the |
@DmitryTsepelev thanks for the kick off! I'm not sure if I understand the need of a validator when using enums. The current implementation raises an error when an invalid value is assigned, e.g. from your examples
I would suggest to keep the same behaviour for an array of enums: When you push an invalid value into the array, it should raise an error. Do you know what I mean? |
@23tux Sorry for the long response, that's a valid point! We don't need to use a validator in the current implementation (however, there is a chance that someone would need to make this behaviour optional in the future) |
Hi! We often have the situation where a model has an array of strings that needs to be validated to only include certain values, and we need some predicate methods to check if a model has a certain value inside this array:
And IMHO, that looks suspiciously like a StoreModel use case: An array of enums. Only difference would be that a wrong role would raise an exception instead of a validation error (but in my case this would be ok).
As far as I can tell, this isn't possible right now with
StoreModel
, am I right? Would it be a feature you would consider to include? I'd be happy to try for a PR if you could give me some hints how to implement a feature like this.The text was updated successfully, but these errors were encountered: