Yes, this is called bi-directional associations and would be a
welcome (if non-trivial) addition in 3.0.
Incidentally it actually only does 1 query, the rest are cache hits,
so at least your database is safe. However it still wastes memory and
can lead to some weirdness and should be fixed.
The has_many :foos, belongs_to :bar case is very easy, but there are
some common corner cases which we'll have to look at. For example
what's the inverse of belongs_to :bar when we have the following
associations to choose from:
has_many :foos, :conditions=>...
has_many :something_else, :class_name=>"Foo"
has_many :important_foos, :through=>...
Ideally we'd just punt on those cases and require users to explicitly
mark associations as inverses with a declaration like
has_many :foos, :conditions ... :inverse_of=>:bar
--
Cheers
Koz
FWIW, that's basically how Sequel handles it, with the :reciprocal
option, though instead of punting by default if multiple associations
match, it picks the first matching association.
Jeremy
The first matching association sounds like it could be prone to
surprises but we could see how it plays out. Fundamentally though
having something that works with explicit declarations only would be a
good start. How we mark the associations is kinda orthogonal to the
associations' behaviour which is the real challenge.
--
Cheers
Koz
Yes, bi-directional associations are a localised implementation of an
identity map. As has been discussed several times before, an identity
map would be a welcome addition to AR, but would be a *lot* of work
given the functionality we support (:select etc) and the strange ways
it can all interact.
Bi-Directional associations would give 99% of the return with much
less of the complication.
--
Cheers
Koz
Correct me if I'm wrong, but an identity map does nothing to help with
unsaved records. For example, if I build children on a parent record,
I should be able to have validates_presence_of :parent in the child
model - but can't.
Of course, this already works fine without an identity map in the
update case, where the parent ID has already been set and so the
record can be found, but create is the hard one. So an identity map
doesn't really solve many problems, though there are potentially
efficiency gains.