@updated, @inversed in BelongsToAssociation

class Ruleset < ApplicationRecord
  has_many :connects, inverse_of: :ruleset
end
class Connect < ApplicationRecord
  belongs_to :ruleset, inverse_of: :connects
end

a = Ruleset.new
c = Connect.new
c.ruleset = a
a.connects
=> #<ActiveRecord::Associations::CollectionProxy []>

So this does not work. But …

a = Ruleset.new
c = Connect.new
a.connects << c
c.association(:ruleset).updated?
=> false

… this doesn’t work well either, and one will notice it only by bad database performance: If this updated flag is not true, then rails will persist the associations in a most inefficient way: it will create the records with the foreign keys nil, and then do updates to fill in the foreign keys, one by one.

It did trigger my NOT NULL constraints, and I was wondering why, because deep_clone() gave no problem saving the same record in an efficient way. (Then I spent hours tracing the execution in single-step, because there was no obvious difference and I didn’t know for what to search.)

This one doesn’t work either:

a = Ruleset.new
c = a.connects.new
c.ruleset = a

Now @updated is true, but @inversed is false, and the database save fails entirely. Only this seems to work:

a = Ruleset.new
c = Connect.new
c.ruleset = a
a.connects << c

Looking closer:

Having @updated = false on the backpointing belongs_to association of a newly created has_many member seems the default behaviour. But then the already known foreign key will not be inserted into the member before it is saved, and create+update will happen. Not sure if this is intentionally so or a flaw.

And @inversed being set to false when a belongs_to is updated, that one comes from a configuration variable config.active_record.has_many_inversing = false and I don’t know what this is supposed to do, but it makes associated records disappear during the save and consequentially validations fail.