ArrayEnum gem for PostgreSQL array columns

gravatar

If you are familiar with Rails Enum module, where values are mapped to integers (or native enum type) in database, you might wonder if a similar approach is available for array columns.

With a little help from the simple array_enum gem, it is now possible.

Having an integer column defined as PostgreSQL array one can assign and read string values, that internally will be stored as integers in database.

class Profile < ActiveRecord::Base
  extend ArrayEnum

  array_enum goals: {"get_fit" => 1, "gain_muscle" => 2, "lose_weight" => 3}
end

profile = Profile.create(goals: ["lose_weight", "gain_muscle"])
profile.goals # => ["lose_weight", "gain_muscle"]

To simplify querying array columns, a handy scope will be generated as well

User.with_goals("gain_muscle")
# => returns users having any of their goals values being "gain_muscle"

that under the hood is making SQL query like WHERE (goals @> ARRAY[2]).

Validations

To simplify validating array attribute values, subset validator is included in the gem.

class CreateProfile
  include ActiveModel::Model

  attr_accessor :goals

  validates :goals, subset: ["get_fit", "gain_muscle", "lose_weight"]
end

CreateProfile.new(goals: ["sit_on_couch_and_watch_tv"]).valid? # => false