Ruby on Rails considerations for using Enum in model

Source: Internet
Author: User
Tags instance method object object ruby on rails

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.