Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a model with a enum type field?

People also ask

What is enum field type?

Enumerated (enum) types are data types that comprise a static, ordered set of values. They are equivalent to the enum types supported in a number of programming languages. An example of an enum type might be the days of the week, or a set of status values for a piece of data.

Is an enum a model?

The definition I have for models is that they represent knowledge. With that logic, an enum should be a model. Moreover, I have seen in some codebases that enums are stored as tables in the DB so that the knowledge is stored in the DB itself and can be accessed later for joins, or from code.

Can enums have fields?

The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields.


Rails 4.1 added ActiveRecord::Enum, which emulates enums using an integer-type column. You can use them as long as you are willing to change the column type to an integer in the database.

To use these enums, put integer in your generate command:

bin/rails generate Work nickname:string sex:integer

Then add a call to enum in the generated model file:

class Work < ActiveRecord::Base
  enum sex: [ :male, :female ]
end

See Enum’s documentation for more details.


You could just use a string and then add validation on the model like this:

validates_inclusion_of :sex, :in => %w( m f )


Unfortunately, the valid column types are: integer, float, datetime, date, timestamp, time, text, string, binary, and boolean

Try making the column a string and using validates_inclusion_of.


Use enum_column to add enum support to active record

https://github.com/mdsol/enum_column