我试图找到一些旧模型,创建一些新模型,如果保存成功则删除旧模型。
这是我的代码(如果不是Rails-y,我道歉):
# find the old pages that are in my book... if my new pages save, delete these
old_pages = Page.where(:book_id => params['pages']['page0']['book_id'])
error_with_page_save = false
params['pages'].each do |t|
t.each do |k|
book_id = k['book_id']
if k['page_type']
tt = get_page_type_id(k['page_type'])
page = Page.new do |t|
t.book_id = k['book_id']
t.sample_text = URI.decode(k['sample_text'])
t.page_position = k['page_position']
t.page_type_id = tt
t.regex = URI.decode(k['regex'])
end
unless page.save!
# HAD AN ISSUE SAVING ONE OF THE NEW PAGES
error_with_page_save = true
end
end
end
end
unless error_with_page_save
puts "if there were no issues, delete all the old ones"
old_pages.delete_all
end
问题是,这会删除新的,因为直到删除才会实际调用find方法。
如何让“.where”方法实际执行?
答案 0 :(得分:1)
最后致电.all
- 这被视为" final"并将立即执行查询
答案 1 :(得分:1)
你可以省去ids。如果数据集很大,这可以消耗更少的资源。
old_page_ids = Page.where(:book_id => params['pages']['page0']['book_id']).pluck(:id)
# ...
Page.where(id: old_page_ids).delete_all