[英]How to validate jsonb array of objects in Rails?
I have a model, called Order
, to which I'd like to add a new jsonb
column called status_updates
. 我有一个名为
Order
的模型,我想向其中添加一个名为status_updates
的新jsonb
列。 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
. 我想验证每个
status_updates
元素的status
属性是否为以下之一: success
, canceled
, processing
。 Additionally, I'd like to validate that each element has a created_at
timestamp. 另外,我想验证每个元素都有一个
created_at
时间戳。
How would you do that in Rails? 您将如何在Rails中做到这一点? Is it possible to do something similar to
enum
for the statuses? 是否可以对状态进行类似于
enum
的操作?
I think if I were you, I might consider creating an OrderStatus
model, something like: 我想如果我是您,我可能会考虑创建一个
OrderStatus
模型,例如:
# == 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: 然后在
Order
,执行以下操作:
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). 现在,每个
OrderStatus
记录将具有一个created_at
值(假设您的OrderStatus
有效并已保存)。 And, status
will be validated as one of the values in the enum
. 并且,
status
将被验证为enum
中的值之一。 As written, status
will default to processing
- which you may or may not want. 按照书面规定,
status
将默认为正在processing
-您可能会或可能不需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.