Why has_many doesn't set target for objects in its collection?

E.g. when

  class Author < ActiveRecord; has_many :posts; end
  class Post < ActiveRecord; belongs_to :author; end

then

  some_author.posts.each {|p| puts p.author.name}

will require additional queries to fetch author for each post.


Could some option to has_many be added to pre-fill the target (in this
case set_author_target for each post)?



Something like:

module ActiveRecord
  module Associations # :nodoc:
    module ClassMethods

      # When called with <tt>:fill_target => name</tt> it will fill
targets in each object in association
      # E.g.: when Author <tt>has_many :posts, :fill_target =>
"author"</tt>
      # then <tt>some_author.posts.each {|m| m.author.name }</tt> will
not require aditional db queries to fetch author for each post
      # (it will use the +some_author+ already from memory)
      #
      # Two methods are created additionally, for the example above it
will be +posts_with_author+ and +posts_without_author+,
      # where just +posts+ is the same as +posts_with_author+

      def has_many_with_fill_target(association_id, options = {},
&extension)
        fill_target = options.delete(:fill_target)
        has_many_without_fill_target(association_id, options,
&extension)

        if fill_target
          module_eval do
            define_method("#{association_id}_with_#{fill_target}") do |
*args|
 
returning( send("#{association_id}_without_#{fill_target}", *args) ) {|
p| p.each {|m| m.send("set_#{fill_target}_target", self) } }
            end
            alias_method_chain association_id, fill_target
          end
        end
      end

      alias_method_chain :has_many, :fill_target

    end
  end
end


--~--~---------~--~----~------------~-------~--~----~
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 [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to