[英]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.