Rails enum without corresponding storage / column

Viewed 799

I have the following model:

class Operation < ApplicationRecord
  enum state: [:started, :restarted, :reloaded, :stopped]
end

However, the underlying table in the Postgres database does not have state column. Although, I can assign value to the state attribute and save model instance, state just is not saved:

op = Operation.new state: :started
op.save!
=> true

This is a desired behaviour for me, I just want to use it in the same way as attr_accessor attributes are used, but with some additional constraints.

The question is, is it fine to use enum this way? Or is it an undefined behaviour and could be changed/fixed in the future?

Official documentation does not answer this question https://api.rubyonrails.org/v6.1.4/classes/ActiveRecord/Enum.html

UPD: yep, as @ricks says I can achieve the same with:

attr_accessor :state
validates :state, inclusion: { in: %i[started reloaded restarted stopped] }, allow_nil: true

but usage of enum is just more convenient for me as it throws exception at assignment time if the value is not from the allowed list.

1 Answers

You can also do this with the attributes api.

class Operation < ApplicationRecord
  attribute :state
  enum state: [:started, :restarted, :reloaded, :stopped]
end

This will give you all the enum exceptions you are looking for (and the rest of the enum methods).

Although it is not in the documentation, it was suggested as a solution in a rails issue.

Related