Here is a minimal test case that forms the basis of my question. Why is it that even though user
is properly saved, the attribute user.id
isn't updated? Attempting to re-find the record in the database fetches it without issue and the id
attribute is properly set.
AFAICT, this is not a matter of trying to auto-increment a composite primary key in sqlite. The same issue occurs with the uuid/PostgreSQL combination as well. The schema only has id
as the primary key with [ :account_id, :id ]
being a separate, unique index.
#!/usr/bin/env ruby
gem "rails", "~> 5.0.2"
gem "composite_primary_keys"
require "active_record"
require "composite_primary_keys"
ActiveRecord::Base.establish_connection(
adapter: "sqlite3",
database: ":memory:"
)
ActiveRecord::Schema.define do
create_table :accounts, force: true do |t|
end
create_table :users, force: true do |t|
t.references :account
t.index [ :account_id, :id ], unique: true
end
end
class User < ActiveRecord::Base
self.primary_keys = [ :account_id, :id ]
belongs_to :account, inverse_of: :users
end
class Account < ActiveRecord::Base
has_many :users, inverse_of: :account
end
account = Account.create!
puts "created account: #{account.inspect}"
user = account.users.build
puts "before user.save: #{user.inspect}"
user.save
puts "after user.save: #{user.inspect}"
puts "account.users.first: #{account.users.first.inspect}"
And the result of running that script is:
~/src
% ./cpk-test.rb
-- create_table(:accounts, {:force=>true})
-> 0.0036s
-- create_table(:users, {:force=>true})
-> 0.0009s
created account: #<Account id: 1>
before user.save: #<User id: nil, account_id: 1>
after user.save: #<User id: nil, account_id: 1>
account.users.first: #<User id: 1, account_id: 1>
Shouldn't user.id be [1,1]
after the first save? If this is a bug, who should I report it to?