How to store enum as string to database in rails

前端 未结 5 1088
广开言路
广开言路 2021-02-05 07:46

How do I create a migration in ruby where the default is a string rather than an Integer, I want to store enum into the database, but I do not want to store it as Integer, becau

5条回答
  •  暖寄归人
    2021-02-05 08:09

    Reading the enum documentation, you can see Rails use the value index of the Array explained as:

    Note that when an Array is used, the implicit mapping from the values to database integers is derived from the order the values appear in the array.

    But it is also stated that you can use a Hash:

    it's also possible to explicitly map the relation between attribute and database integer with a Hash.

    With the example:

    class Conversation < ActiveRecord::Base  
      enum status: { active: 0, archived: 1 }  
    end
    

    So I tested using Rails 4.2.4 and sqlite3 and created an User class with a string type for sex type and a Hash in the enum with string values(I am using fem and mal values to differ from female and male):

    Migration:

    class CreateUsers < ActiveRecord::Migration
      def change
        create_table :users do |t|
          t.string :sex, default: 'fem'
        end
      end
    end  
    

    Model:

    class User < ActiveRecord::Base
      enum sex: { female: 'fem', male: 'mal' }
    end
    

    And in console:

    u = User.new
    #=>  #
    u.male?
    #=> false
    u.female?
    #=> true
    u.sex
    #=> "female"
    u[:sex]
    #=> "fem"
    u.male!
    # INSERT transaction...
    u.sex
    #=> "male"
    u[:sex]
    #=> "mal"
    

提交回复
热议问题