简体   繁体   English

在Rails 5中更新模型上的特定属性

[英]Updating specific attributes on models in Rails 5

I very new to rails 5 and need a hand with some syntax.. 我对Rails 5非常陌生,需要使用一些语法。

I have two models Saving and Investment .. Each Saving can have many Investments so the relation is 1:m. 我有两个模型SavingInvestment ..每个Saving可以有很多投资,因此该关系为1:m。 Both models have an boolean attribute is_autobid . 这两个模型都具有boolean属性is_autobid

I want to create a rake task that retrieves all Savings where is_autobid = true and then updates the first investments of a particular Saving record to true .. so far I have: 我要创建一个瑞克任务,以检索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

You can use update_column for updating single column it will not check for any validations and you need to only update investment if any record is found 您可以使用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

Update 更新资料

If you want to load all records at once, than you can do it with below query 如果要一次加载所有记录,则可以使用以下查询来完成

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM