Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Global ActiveRecord::Enum

I really like Rails 4 new Enum feature, but I want to use my enum

enum status: [:active, :inactive, :deleted]

in every model. I cannot find any way how to declare for example in config/initializes/enums.rb and include every model

I'm very new in Ruby on Rails and need your help to find solution

like image 648
Irakli Lekishvili Avatar asked Sep 19 '14 15:09

Irakli Lekishvili


People also ask

What is enum in Ruby on Rails?

In Ruby on Rails, an enum is an attribute where the values map to integers in the database and can be queried by name. For example, we could define an enum for the status attribute, where the possible values are pending , active , or archived . Ruby on Rails added support for enums in Rails 4.1.

Is enum good for Android?

UPDATE 2019: Enums are fine to use in Android since ART replaced DALVIK as runtime environment stackoverflow.com/a/56296746/4213436.

What are enum types?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.


1 Answers

Use ActiveSupport::Concern this feature created for drying up model codes:

#app/models/concerns/my_enums.rb
module MyEnums
  extend ActiveSupport::Concern

  included do
    enum status: [:active, :inactive, :deleted]
  end
end

# app/models/my_model.rb
class MyModel < ActiveRecord::Base
  include MyEnums
end

# app/models/other_model.rb
class OtherModel
  include MyEnums
end

Read more

like image 104
Philidor Avatar answered Oct 19 '22 02:10

Philidor