我需要有關如何洗掉資料庫中存在但不在請求中發送的陣列中的記錄的幫助;
My Array:
[
{ "id": "509",
"name": "Motions move great",
"body": "",
"subtopics": [
{
"title": "Tywan",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp Audio 2021-09-24 at 13.57.34.mpeg"
},
{
"title": "Transportations Gracious",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp Audio 2021-09-24 at 13.57.34.mpeg"
},
{
"title": "Transportation part",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp Audio 2021-09-24 at 13.57.34.mpeg"
}
]
},
{
"name": "Motions kkk",
"body": "",
"subtopics": [
{
"title": "Transportations",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp Audio 2021-09-24 at 13.57.34.mpeg"
}
]
}
]
下面是我的實作:哪里出錯了?
@topics = @course.topics.map{|m| m.id()}
@delete= @topics
puts @delete
if Topic.where.not('id IN(?)', @topics).any?
@topics.each do |topic|
topic.destroy
end
end
uj5u.com熱心網友回復:
我不清楚,在您的代碼中,您選擇在您之前顯示的陣列中發送的 id ......所以我假設是這樣的:
objects_sent = [
{ "id": "509",
"name": "Motions move great",
"body": "",
"subtopics": [
{
"title": "Tywan",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp Audio 2021-09-24 at 13.57.34.mpeg"
},
{
"title": "Transportations Gracious",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp Audio 2021-09-24 at 13.57.34.mpeg"
},
{
"title": "Transportation part",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp Audio 2021-09-24 at 13.57.34.mpeg"
}
]
},
{
"name": "Motions kkk",
"body": "",
"subtopics": [
{
"title": "Transportations",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp Audio 2021-09-24 at 13.57.34.mpeg"
}
]
}
]
因為你有這樣的陣列,所以你需要在資料庫上查詢的唯一資訊是 id(另外,假設陣列中的 id 是資料庫上的 id,否則就沒有意義了)。你可以像這樣得到它們:
sent_ids = objects_sent.map{|o| o['id'].to_i}
另外,在我看來,對于您展示的代碼,您想根據特定課程銷毀它們。有兩種方法可以做到這一點。首先,使用關系(我更喜歡這種關系):
@course.topics.where.not(id: sent_ids).destroy_all
或者您可以直接在 Topic 模型上進行查詢,但傳遞 course_id 引數:
Topic.where(course_id: @course.id).where.not(id: sent_ids).destroy_all
ActiveRecord 足夠聰明,可以以兩種方式正確掛載該查詢。給它一個測驗,看看哪個更適合你
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/455228.html
上一篇:macOSMonterey(12.3)上的Jekyll問題
下一篇:在Flutter中隨機顯示影像
