2016-03-17 12 views
0

我的課程模型有一個名爲user_ids的字段,它是一個ObjectIds數組。空字段的有效記錄delete_all問題

我試圖找到所有非空user_id的課程,並只取消user_id字段。

list = Course.where({ :user_ids.nin => [[], nil] }) 
list.each do |course| 
    course.user_ids = [] 
    course.save 
end 

但是,我似乎總是得到具有兩門課程:

"user_ids" : [ ObjectId("560dc9998b3c5b003f000000") ] 

是我的查詢錯了嗎?任何幫助表示讚賞。

+0

你的問題是,你想找到所有具有空或無'user_ids'的課程,然後將它們設置爲'[]'。所以你想找到有'user_ids == []'的課程並將其設置爲'[]'...?爲什麼?這聽起來像你想要設置一些與它已有的東西相同的東西。 – yez

+0

對不起,不是空的。編輯Q. – premunk

回答

1

我想你想使用where.not方法。

Course.where.not(user_ids: [[], nil])

You can read more about where.not here

原始查詢沒有工作的原因是因爲你試圖呼籲:user_id符號.nin方法,這是不是一個符號都可以接受的方法。

+0

同意。但是,你能解釋爲什麼我的失敗嗎? – premunk

+0

爲解釋代碼失敗的原因進行了編輯。 – yez