1

I am struggling to make work my Catalog with enum within a class, from this tuto : https://naturaily.com/blog/ruby-on-rails-enum.

My models :

**app/models/catalog.rb**
class Catalog < ApplicationRecord
  include ArrayToEnumHash
  enum state: array_to_enum_hash(CatalogState::STATES)

  def state
    @state ||= CatalogState.new(read_attribute(:state))
  end
end
**app/models/catalog_state.rb**
class CatalogState
  STATES = %w(incoming in_progress finished).freeze

  def initialize(state)
    @state = state
  end

  # what you need here
end
**app/concerns/array_to_enum_hash.rb**
module ArrayToEnumHash
  extend ActiveSupport::Concern
  def array_to_enum_hash(array)
    result = {}
    v = array.to_enum
    w = array.map {|v| v.to_sym }.to_enum
    loop do
      result[w.next] = v.next
    end
    result
  end
end
**db/schema.rb**
create_enum :catalog_state, [
    "incoming",
    "in_progress",
    "finished",
  ]

create_table "catalogs", force: :cascade do |t|
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.enum "state", enum_name: "catalog_state"
    t.index ["state"], name: "index_catalogs_on_state"
  end

My Catalog seems fine :

#<Catalog:0x00007fe87dbfb810
 id: 3,
 created_at: Thu, 02 Jul 2020 16:52:36 UTC +00:00,
 updated_at: Fri, 03 Jul 2020 19:51:26 UTC +00:00,
 status: "unset",
 auction_type: "internet",
 state: "in_progress">

However, on my console, ActiveRecord doesn't build the enum shortcuts :

[5] pry(main)> c.state
=> "in_progress"
[6] pry(main)> c.in_progress?
NoMethodError: undefined method `in_progress?' for #<Catalog:0x00007fe87dbfb810>
from /Users/pierre/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activemodel-6.0.3.2/lib/active_model/attribute_methods.rb:432:in `method_missing'

WTF ?

7
  • 1
    I must ask where do create_enum and t.enum come from? Jul 4, 2020 at 7:16
  • My aim here is to create the direct access methods. to go further than the integer & array setup : instead of the array ["incoming", "in_progress", "finished"] , I set up the hash {:incoming=>"incoming", :in_progress=>"in_progress", :finished=>"finished"}, so that I can directly access to : my_instance.incoming? => false , my_instance.incoming!. So the question is about the helper setup, which seems to be right but doesn't work.
    – pierrecode
    Jul 4, 2020 at 11:05
  • 1
    But you don't need to do that by yourself. That's handled by Rails :D, take a look to the docs; "... the bang and predicate methods along with the associated scopes are now prefixed and/or suffixed accordingly". Jul 4, 2020 at 11:07
  • 1
    If the use you're going to give to that enum column needs something ActiveRecord can not provide you, you can use the gem. Otherwise, the example I gave in the answer must be enough to start with it. Jul 4, 2020 at 14:25
  • 1
    You can anyway do, it's not directly attached to the use of the gem. Although, I must mention that if you're going to hardcode all those "voivodeship"s, why not store them in your database? The approach might have pros, but also cons. Food for thought. Jul 4, 2020 at 14:28

1 Answer 1

1

You don't need that much in order to add an "enum" column in your catalogs table.

class CreateCatalogs < ActiveRecord::Migration[6.0]
  def change
    create_table :catalogs do |t|
      t.string "status"
      t.string "auction_type"
      t.integer "state"
      t.timestamps
    end
  end
end

An enum column can be represented with an integer data type column, there t.integer "state".

An in order to set the enum values, you can just call the constant defined in CatalogState:

class Catalog < ApplicationRecord
  enum state: CatalogState::STATES
end

The values will be ["incoming", "in_progress", "finished"], otherwise, using the helper method in the concern it'll be like {:incoming=>"incoming", :in_progress=>"in_progress", :finished=>"finished"}, and there, Rails has no way to infer the integer value they represent.

After that you can try it:

catalog = Catalog.new(id: 3, created_at: 'Thu, 02 Jul 2020 16:52:36 UTC +00:00', updated_at: 'Fri, 03 Jul 2020 19:51:26 UTC +00:00', status: 'unset', auction_type: 'internet', state: 'in_progress')
catalog.valid? # true
catalog.save
Catalog.last
# Catalog Load (0.3ms)  SELECT "catalogs".* FROM "catalogs" ORDER BY "catalogs"."id" DESC LIMIT $1  [["LIMIT", 1]]
# => #<Catalog:0x00007fc4d9448f90 id: 3, status: "unset", auction_type: "internet", state: "in_progress", created_at: Thu, 02 Jul 2020 16:52:36 UTC +00:00, updated_at: Fri, 03 Jul 2020 19:51:26 UTC +00:00>
Catalog.last.in_progress?
# Catalog Load (0.5ms)  SELECT "catalogs".* FROM "catalogs" ORDER BY "catalogs"."id" DESC LIMIT $1  [["LIMIT", 1]]
# => true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.