How to store enum as string to database in rails

前端 未结 5 1084
广开言路
广开言路 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:31

    I normally do the following:

    # in the migration in db/migrate/…
    def self.up
      add_column :works, :status, :string, null: false, default: 'offering'
    end
    
    # in app/models/work.rb
    class Work < ApplicationRecord
      ALL_STATES = %w[canceled offering running payment rating done].freeze
    
      enum status: ALL_STATES.zip(ALL_STATES).to_h
    end
    

    By using a hash as argument for enum (see docs) this stores strings in the database. At the same time this allows you to use all the cool Rails helper methods:

    w = Work.new
    #=>  #
    w.rating?
    #=> false
    w.offering?
    #=> true
    w.status
    #=> "offering"
    w[:status]
    #=> "offering"
    w.done!
    # INSERT transaction...
    w.status
    #=> "done"
    w[:status]
    #=> "done"
    

提交回复
热议问题