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: monkey patching, ruby on rails

Very cool feature. Great that this service works on any site not just blogs.
Wow thanks! I’m a regular reader and enjoy your work. Keep it up!
I am also Kevin Watt. That's all
Looks nice and works ;) thanks!
Kevin, may I ask do you work on something else for the moment? Coz I can't find anything new at this hub...
Really good work, I've just tried and I like it very much. Thanks!
I can see why a lot of people would really enjoy your links here.
Looks nice and works thanks!
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