On Thu, Apr 23, 2009 at 9:16 AM, kscaldef <kevin.scaldefe...@gmail.com> wrote: > > I had a closely related question today, which was why this code does N > +1 queries? > > order.order_items.each {|oi| oi.order} > > Why must each order item do a query to find its order? It seems like > Rails should recognize the reciprocal nature of the associations.
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 --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group. To post to this group, send email to rubyonrails-core@googlegroups.com To unsubscribe from this group, send email to rubyonrails-core+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/rubyonrails-core?hl=en -~----------~----~----~----~------~----~------~--~---