Search code examples
ruby-on-railsruby-on-rails-5psqlrails-console

Update_all query with joins in rails console


I have an trackers table and applications tables

application.rb has_many :trackers

tracker.rb

belongs_to :application

What I trying to do is update the check_in_date in the trackers table to be query to begin_date in the applications tables only for those records which have check_in_date is equal to "2019-05-30".

I am trying to run the command below but I am getting an error.

Tracker.joins(:application).where("check_in_date = ?", "2019-05-30").update_all("tracker.check_in_date = application.begin_date")

error

ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "application")

Any idea where i am going wrong.


Solution

  • Maybe try this:

    Note I have no idea if this will work so don't do it in production unless you can confirm

      Tracker.where(check_in_date: "2019-05-30")
        .update_all("check_in_date = (#{  
             Application.select(:begin_date)
               .where('applications.id = trackers.application_id').to_sql})"
      )
    

    The theory is that this should result in the following SQL

      UPDATE trackers 
      SET check_in_date = (
         SELECT 
            begin_date
         FROM 
            applications 
         WHERE 
            applications.id = trackers.application_id
      ) 
      WHERE 
        trackers.check_in_date = "2019-05-30"