For one thing, I don't think it's appropriate to write something like l.storables << Storable.create
.
By writing this, two things happens:
Storable.create
creates a new Storable object withlocation_id
nill.storables <<
updates the object created, sets location_id tol.id
, and somehow forgets to update the counter cache.
It might be ActiveRecord's fault, since it should have been smarter, but you've actually executed two SQL(insert into storable & update storable set location_id = something) simply to insert a new storable record. Anyway it's a bad idea, and if you have a foreign key constraint on location_id, the first insert would even fail.
So use l.storables << Storable.new
instead
PS: With l.storables << Storable.create
, since the return value of Storable.create
is not a new record, it's a bit hard for l
to decide what to do. In some cases, it needs to increment its own counter cache, in other cases, it needs to increment its own counter cache and decrement someone else's counter cache, or it might need to do nothing.