The role of enum is to declare an enumeration property to map the value of an integer field in the database and to query the database through this property.
This can be used (the case comes from the official), such as:
class conversation < ActiveRecord::Base enum status: [:active, :archived]end
or
class conversation < activerecord::base enum statusactive0, archived: 1}end
# conversation.update! status:0Conversation.active!Conversation.Active?# = TrueConversation.Status# = "Active"# conversation.update! Status:1Conversation.archived! conversation. archived? # = trueconversation. Status # = "archived" # conversation.status = 1 conversation. status = "archived" conversation.status = nil Conversation. status. nil? # = trueconversation. Status # = nil
about query:
Conversation.where(status: [:active, :archived])Conversation.where.not(status: :active)
This is easy to use, but it's important to be very careful when using this enum, and you may notice that it produces some methods. For example above, it produces:active!
,active?
, < span class= "identifier" > status= and so on.
< span class= "identifier" > If you accidentally used: Group property , such as the definition:
class Conversation < ActiveRecord::Base enum status: {group: 0, single: 1}end
At run time it will produce a tried to define an enum named "Statuss" on the Model "Confirmasset", but this would generate a class method "Gro Up ", which are already defined by Active Record. Such errors.
Also pay attention when using the field name, because I got the error: You tried to define an enum named "Import" on the Model "Confirmasset", but this will generate A instance method "Import=", which is already defined by another enum.
Ruby on Rails considerations for using Enum in model