Search code examples
ruby-on-railsrubyruby-on-rails-5rake-task

Updating specific attributes on models in Rails 5


I very new to rails 5 and need a hand with some syntax..

I have two models Saving and Investment .. Each Saving can have many Investments so the relation is 1:m. Both models have an boolean attribute 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:

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

Solution

  • 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

    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