【发布时间】:2015-04-13 18:15:51
【问题描述】:
我将课程列表文档嵌入到名为课程的父文档中。课程列表属于示范课程。
课程表模型:
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 是什么意思?有没有办法将它覆盖到一个不涉及 $ 作为前缀的键?
-
如何验证课程列表中所有对象的课程 ID?现在我已经写了这个但是它不起作用:(
validate :validate_courselist def validate_courselist if (courselist == nil) return end if (courselist.uniq.length != courselist.length) errors.add :base, "Course ids should be unique" end courselist.each do |course_id| if (Models::Persistence::Course.find_by( _id: course_id) == nil) #this is my issue. How can I get the $oid of the course object?? errors.add :base, "Course id #{course_id} could not be found" end end结束 Edit1:上述验证是在嵌入式父模型上完成的。应该在孩子身上做吗?还是在父母那里?还是没关系? 提前致谢。
【问题讨论】:
标签: ruby validation activerecord mongoid