BelongsToMany: can't reset column to empty array with defaults
Created by: yosiat
Hi,
Checked the latest commit, following the discussion here - https://github.com/crashtech/torque-postgresql/issues/56#issuecomment-777657238
# 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.timestamps
end
execute "alter table projects add column employees_ids integer[] default '{}'::integer[]"
end
class Employee < ActiveRecord::Base
has_many :projects, array: true, foreign_key: :employees_ids
end
class Project < ActiveRecord::Base
belongs_to_many :employees, foreign_key: "employees_ids"
end
class BugTest < Minitest::Test
def test_bug
employee = Employee.create!
project = Project.create!(employees_ids: [employee.id])
# Accessing `project.employees`, cause the next update to get dismissed
pp project.employees
project.update(employees_ids: [])
project.reload
pp project.employees_ids
pp project.employees
end
end
I am trying to update the employee_ids
to be an empty array, and it doesn't work.
This happens because ids_reader
takes the ids from the target (while the target is stale)