[英]Updating specific attributes on models in Rails 5
我對Rails 5非常陌生,需要使用一些語法。
我有兩個模型Saving
和Investment
..每個Saving可以有很多投資,因此該關系為1:m。 這兩個模型都具有boolean屬性is_autobid
。
我要創建一個瑞克任務,以檢索is_autobid = true
所有儲蓄,然后將特定儲蓄記錄的首次投資更新為true ..到目前為止,我有:
task :update_autobids => :environment do
Saving.where(is_autobid: 1).all.each do |s|
investment = s.investments.first(:is_autobid, 0)
investment.update(is_autobid = 1)
end
end
您可以使用update_column更新單列,它將不檢查任何驗證,並且僅在找到任何記錄時才需要更新投資
Saving.where(is_autobid: 1).each do |s|
investment = s.investments.find_by(is_autobid: 0)
investment.update_column(:is_autobid, 1) if investment
end
更新資料
如果要一次加載所有記錄,則可以使用以下查詢來完成
investments = Investment.includes(:saving).where("savings.id = (select id from savings where savings.is_autobid = 0 limit 1)").references(:saving)
investments.each do |investment|
investment.update_column(:is_autobid, 1)
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.