thetron / mongoid-enum

Sweet enum sugar for your Mongoid documents
MIT License
117 stars 166 forks source link

'default' value can not be set if it's not in the list. #7

Closed zpengyu closed 9 years ago

zpengyu commented 10 years ago

I have the code like enum :gender, [:male, :female], default: '' doesn't work.

If I don't set a value, I got The following errors were found: gender is not included in the list

thetron commented 10 years ago

The gem should (maybe?) have options for allow_blank and/or allow_nil - but there's currently nothing there.

If you want this feature, you'll probably need to disable the built-in validations and use your own activemodel validation.

p3drosola commented 10 years ago

From reading the gem's code I understand it should be:

enum  :gender, [:female, :male], {default: nil, required: false}

?

hoang1417 commented 10 years ago

This won't work even you add validate: false to the declaration. Maybe an issue?

But I think it makes sense and no need to make other extend options. Because we cannot fully control what is the list of available values of an enum field, considering that validate: false works and we define enum like this:

in app/model/order.rb

enum :food, FOOD_LIST, default: :orange_juice, validate: false

in config/initializers/constants.rb

FOOD_LIST = [:chicken, :hotdog, :hamburger]

There're may some inconsistent values because that are not defined in one place.

p3drosola commented 10 years ago
enum :food, FOOD_LIST, default: FOOD_LIST.first
hoang1417 commented 10 years ago

@p3drosola, it's a good config but we are talking about the case when default value is not in the list (FOOD_LIST).

thetron commented 9 years ago

I've finally gotten around to looking through this issue in detail and @p3drosola got this one right - if you want to allow nil values, then passing an option of required: false is the way to go. It might be worth renaming this in the future to allow_nil, to make it a bit more consistent with the Rails API though.

@hoang1417 If you do have an edge case where the default value is mysteriously required to not be in the list of options, then you're probably best off disabling validations and rolling your own solution that works.

Hope this answers everyone's questions - if I've missed the point completely, feel free to add to the discussion and i'll reopen the issue :smile: