0

I have a model, called Order, to which I'd like to add a new jsonb column called status_updates. This column will contain data of the following format:

status_updates = [{ status: 'success', created_at: <timestamp> }, { status: 'processing', created_at: <timestamp> }]

I would like to validate the status attribute of each status_updates element is one of the following: success, canceled, processing. Additionally, I'd like to validate that each element has a created_at timestamp.

How would you do that in Rails? Is it possible to do something similar to enum for the statuses?

1 Answer 1

3

I think if I were you, I might consider creating an OrderStatus model, something like:

# == Schema Information
#
# Table name: order_statuses
#
#  id               :bigint           not null, primary key
#  status           :integer          default(0)
#  order_id         :integer
#  created_at       :datetime         not null
#  updated_at       :datetime         not null
#
class OrderStatus < ApplicationRecord
  belongs_to :order
  validates :status, 
            presence: true,
            inclusion: { in: 0..2 }

  enum status: {
    processing:     0,
    success:        1,
    cancelled:      2,
  }

end

And then in Order, do something like:

class Order < ApplicationRecord
  has_many :order_statuses 
end

Now, every OrderStatus record will have a created_at value (assuming your OrderStatus is valid and saved). And, status will be validated as one of the values in the enum. As written, status will default to processing - which you may or may not want.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.