Best way to store Enum value in ActiveRecord and convert to string for display

前端 未结 5 1787
野的像风
野的像风 2021-02-02 17:05

I am trying to figure out what is the best way to store an enum value in activerecord but convert it to a \'title\' for display in an app.

I.E.

Review Enum:

5条回答
  •  情深已故
    2021-02-02 17:32

    ActiveRecord enums is the best way to go since it's a part of the framework (since version 4.1).

    Its usage is quite simple:

    Migration:

    class AddEnumToMyModel < ActiveRecord::Migration
      def change
        add_column :my_model, :status, :integer, default: 0
      end
    end
    

    Model:

    class MyModel < ActiveRecord::Base
      enum status: [:draft, :beta, :public]
    end
    

    Then use it a will:

    MyModel.draft # gets all drafts
    MyModel.last.draft? # checks if the last model is draft
    MyModel.last.status # gets the string description of the status of my model
    

    For mode information refer to documentation.

提交回复
热议问题