NoBrainerORM / nobrainer

Ruby ORM for RethinkDB
http://nobrainer.io/
Other
387 stars 49 forks source link

How do I create an optional (not required) Enum field? #238

Closed nrser closed 7 years ago

nrser commented 7 years ago

Just started out with NoBrainer, so forgive me if I am obviously missing something.

This doesn't seem to work:

class SKU
  include NoBrainer::Document
  include NoBrainer::Document::Timestamps

  belongs_to :design

  field :size, 
        type: Enum,
        in: [:small, :medium, :large, :xlarge],
        required: false
end
SKU.create! id: 'blah', design: Design.first

Errors like

#<SKU id: "blah"> is invalid: Size is not included in the list

For what it's worth I also tried

SKU.create! id: 'blah', design: Design.first, size: nil

which seems to make no difference, and

class SKU
  include NoBrainer::Document
  include NoBrainer::Document::Timestamps

  belongs_to :design

  field :size, 
        type: Enum,
        in: [nil, :small, :medium, :large, :xlarge]
end

which pukes on the nil:

RuntimeError:
  The `:in` option must specify symbol values

Thanks in advance, Neil.

jeroenvisser101 commented 7 years ago

Hi Neil,

The Enum type uses the :in symbol which it uses internally to check if all values are symbols, but it's also passed on to active_model (which NoBrainer uses internally), which is raising the "Size is not included in the list" error. I believe nilifying this value isn't possible right now.

I'm not sure if this is by design, but it's definitely not meant to accept any nil value right now.

You might want to create a :default size and set that?

— Jeroen

nrser commented 7 years ago

Thanks for responding so rapidly. I understand it's not in your code. A default doesn't make sense for this situation, and just from searching and reading about ActiveRecord's Enum for a few minutes it seems like kind of a mess; I think I'll just use a different approach.