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

前端 未结 5 1778
野的像风
野的像风 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条回答
  •  梦毁少年i
    2021-02-02 17:54

    I agree with @tamersalama. Here's a simple way to do it using strings in the DB with a custom Enum class. Note that this also supports human readable names for use in dropdown menus.

    https://gist.github.com/alexch/a7be54e1b085718473ff

    SQL:

    Table name: snacks
     id                         :integer
     ice_cream                  :string
    

    Rails:

    class Snack < ActiveRecord::Base
      FLAVORS = Enum.new [
          [:vanilla, "Vanilla"],
          [:chocolate, "Chocolate"],
          [:rocky_road, "Rocky Road"]
          ])
      ]
    end
    

    HTML:

    <%= simple_form_for @snack do |f| %>
    <%= f.collection_select :ice_cream, Snack::FLAVORS, :value, :label %>
    <% end %>
    

提交回复
热议问题