简体   繁体   English

如何在Rails中验证对象的jsonb数组?

[英]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属性是否为以下之一: successcanceledprocessing 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM