BelongsToMany: calls after_commit on the associated object
Created by: yosiat
Hi!
I did the migration to torque weeks ago and now I notified different behaviour other than "has_and_belongs_to_many" from rails.
# frozen_string_literal: true
require 'torque-postgresql'
require 'byebug'
require "active_record"
require "minitest/autorun"
require "logger"
ActiveRecord::Base.establish_connection(
adapter: "postgresql",
database: "test",
encoding: "unicode",
host: "localhost",
port: "5432",
password: "12345",
username: "test")
ActiveRecord::Schema.define do
drop_table "employees", if_exists: true
drop_table "projects", if_exists: true
create_table "employees" do |t|
t.string "name"
t.timestamps
end
create_table "projects" do |t|
t.string "title"
t.bigint "employees_ids", array: true
t.timestamps
end
end
class Employee < ActiveRecord::Base
has_many :projects, array: true, foreign_key: :employees_ids
after_commit :on_update, on: :update
def on_update
puts "Employee got updated"
end
end
class Project < ActiveRecord::Base
belongs_to_many :employees, foreign_key: "employees_ids"
end
employee = Employee.create!
project = Project.create!
puts "Adding employee to project"
project.employees << employee
pp project.reload.employees_ids
When doing concat, both objects get after_commit on update calls, for Project, it makes sense since its employees_ids has changed, but for Employee, it doesn't make sense since nothing is changed there.
To overcome this after_commit callback, right now I need to add a check for return if saved_changes.empty?
which I prefer to avoid.
Is there anyway to stop those after_commit calls?