I have a find with a has_many relationship using :include for the relationship. My question is how do i add an additional column to the query and keep all the associations in tact? I need to add a distance column in the output for some geocoding but can not figure out how to do this without being forced to find_by_sql.
I'll assume that the "column" in question isn't in any table but being
computed on the fly. If so, simply modify the ':select =>' parameter to
add your additional column. I.e.
Model.find(:all, :select => '*, insert_ugly_trig_formula_here AS
distance', :conditions => etc. etc.)
Notice the '*,' so that you still get the other columns you (and
ActiveRecord) normally expect. Once the query returns you'll have an
@object.distance method you can call that gives you the computed
distance for that record.
Does this work as well with eager loading ? Thats why I included that i was using :include as well in my find. Just want to make sure that is not going to throw this in a hissy, because i have been trying :select with eager loading and not having any luck.
Actually, no. Eager loading with :include => overwrites anything you
put in the :select => parameter, so you can’t do both. Sorry, I
didn’t pick up on the importance of the eager loading in your original
question.
Thats what I thought. Any suggestions on a workaround? The only other thing I was thinking was somehow using a postgresql function or view to make an additional column available at the postgres level.
The one time I’ve tried to do this, I didn’t actually need to eager
load, I just needed to include other tables in the SELECT function and
the WHERE conditions, so I used :joins => instead of :include =>
and that worked well for me. That may not work for you though. Your
other options are, A) not eager load, or B) compute ‘distance’ for each
item later on in a separate method.