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

前端 未结 5 1834
野的像风
野的像风 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:43

    While I agree that @Godsaur answer is correct - I personally don't like the approach of storing integer values to represent meaningful string equivalents (provided that enough database indexing is made and/or the cost of querying strings in the DB engine is similar to that of querying integers).

    My approach is usually storing the text values in the database (for easier understanding of DB records).

    my_model.rb

    class MyModel < ActiveRecord::Base
    
      STATUSES = HashWithIndifferentAccess.new({unverified: 'unverified', reviewed: 'reviewed', flagged: 'flagged'})
      #the text values are similar to their symbols key
      #you could also define additional attributes for each key if needed. Ex:
      #STATUSES = {unverified: {title: 'Unverified Text Title', txt: 'unverified'}, ...}
    
      # assuming a 'status' field
      scope :unverified, -> { where(status: STATUSES[:unverified]) }
    
      def unverified?
        status == STATUSES[:unverified]
      end
    
      # Or
      STATUSES.each do |sym, val|
        define_method("#{sym}?") {status == val}
      end
    end
    

    my_view.erb

    <%= MyModel::STATUSES[@my_model.status] %> or 
    <%= MyModel::STATUSES[@my_model.status].title %>
    

提交回复
热议问题