Rails: Hack belongs_to to allow :select

Posted by kevin Tue, 17 Apr 2007 22:57:35 GMT

For some reason most rails associations allow :select as a parameter to limit which rows are loaded, but belongs_to doesn't.

Here's my (only rudimentarily tested) monkey-patch to add it:

module ActiveRecord::Associations::ClassMethods
  def create_belongs_to_reflection(association_id, options)
    $stderr.puts "MAKING REFLECTION"
    options.assert_valid_keys(
      :select, #added
      :class_name, :foreign_key, :foreign_type, :remote, :conditions, :order, :include, :dependent, 
      :counter_cache, :extend, :polymorphic
    )
    
    reflection = create_reflection(:belongs_to, association_id, options, self)

    if options[:polymorphic]
      reflection.options[:foreign_type] ||= reflection.class_name.underscore + "_type"
    end

    reflection
  end
end
module ActiveRecord
  module Associations
    class BelongsToAssociation  @reflection.options[:select] || '*', #added
          :conditions => conditions,
          :include    => @reflection.options[:include]
        )
      end
    end
  end
end

Technorati Tags: ,

Posted in  | 9 comments

Comments

  1. Bill said 16 days later:
    Very cool feature. Great that this service works on any site not just blogs.
  2. Jimy T. said 20 days later:
    Wow thanks! I’m a regular reader and enjoy your work. Keep it up!
  3. Kevin Watt said 35 days later:
    I am also Kevin Watt. That's all
  4. Led said 35 days later:
    Looks nice and works ;) thanks!
  5. Arnod said 77 days later:
    Kevin, may I ask do you work on something else for the moment? Coz I can't find anything new at this hub...
  6. Edwin said 86 days later:
    Really good work, I've just tried and I like it very much. Thanks!
  7. Very Kewel Site said 133 days later:
    I can see why a lot of people would really enjoy your links here.
  8. andrew said 334 days later:
    Looks nice and works thanks!
  9. Martin said 392 days later:
    hey kevin i heard you created The Ap site i was wondering if you could help me with the scritp for the chatterbox you have there my email is morbid.maney@gmail.com

(leave url/email »)