Ruby 使用嵌入文档时的ActiveRecord嵌套验证:Mongoid
我正在将courselist文档嵌入名为“课程”的父文档中。课程列表属于示范课程 课程列表模式:Ruby 使用嵌入文档时的ActiveRecord嵌套验证:Mongoid,ruby,validation,activerecord,mongoid,Ruby,Validation,Activerecord,Mongoid,我正在将courselist文档嵌入名为“课程”的父文档中。课程列表属于示范课程 课程列表模式: include Mongoid::Document @schema = { 'type' => 'object', 'properties' => { # 'id' => { 'type' => 'string' }, 'course_order_id' => {
include Mongoid::Document
@schema = {
'type' => 'object',
'properties' => {
# 'id' => { 'type' => 'string' },
'course_order_id' => { 'type' => 'integer'}, #Explicit course ID order
'course_id' => { 'type' => 'string' }
}
}
@modelName = 'courselist'
@collectionName = 'courselist'
field :course_order_id, type: Integer
belongs_to :course #Course model
embedded_in :curricula, class_name:"Models::Persistence::Curriculum"
课程.rb
@schema = {
'type' => 'object',
'properties' => {
'id' => { 'type' => 'string' },
'title' => { 'type' => 'string' },
'description' => { 'type' => 'string' },
'cover_image_url' => { 'type' => 'string' },
'trailer_url' => { 'type' => 'string' },
'courselist' => {'type' => 'array'},
'price' => { 'type' => 'float' },
'currency_id' => { 'type' => 'string' },
'publisher_id' => { 'type' => 'string' },
'certification_ids' => { 'type' => 'array' },
'version' => { 'type' => 'integer' },
'status' => { 'type' => 'string'}
}
}
@modelName = 'curricula'
@collectionName = 'curricula'
store_in collection: 'curricula'
field :title, type: String
field :description, type: String
embeds_many :courselist
在路由上执行get时获得的JSON:
"id": "552bfae243534fcdd2a20000",
"courselist": [
{
"_id": {
"$oid": "552bfae243534fcdd2a30000"
},
"course_order_id": 1,
"course_id": {
"$oid": "552bfae143534fcdd2930000"
}
},
{
"_id": {
"$oid": "552bfae243534fcdd2a40000"
},
"course_order_id": 2,
"course_id": {
"$oid": "552bfae243534fcdd29f0000"
}
}
]
}
我的疑问是:
这个
$oid
东西正是BSON::ObjectId
将自身序列化为JSON的方式。您可以自己打开它,或者,如果您想在您的模型实例上继续使用作为JSON
和作为JSON
,您可以使用monkey patchBSON::ObjectId
:
module BSON
class ObjectId
def to_json(*)
to_s.to_json
end
def as_json(*)
to_s.as_json
end
end
end
我使用monkey-patch来避免一直处理$oid
之类的东西
就验证而言,我会让每件事都验证其级别的数据。您有两个单独的验证:
课程
将处理整个列表:
validate :no_duplicates
def no_duplicates
if(course_list.map(&:course_id).uniq.length != course_list.length)
#...
end
end
请注意,我们正在查看嵌入文档中的\u id
以检查唯一性。每个嵌入文档都有自己的\u id
,而\u id
通常用于比较;我们不关心这些,我们关心的是唯一的课程,所以这就是我们所关注的
然后,您的课程列表
可以考虑其自身的有效性:
validates_presence_of :course
检查课程的存在性将尝试将课程从MongoDB中拉出。如果您认为这太昂贵,可以用直接存在性检查代替
validates_presence_of :course