Help needed to construct complex query

Hi all,

I am really trying to not use a native sql statement for the
following.

Basically, I am trying to solve the same problem described here:

However, I need to do this in a parent child relationship.

Parent object contains (Latitude, Longitude, name, …), Child object
contains (expired_time, start_time, …) and it is a has_many
relationship.

here is my code:

distance_formula = “( 3959 * acos( cos( radians(#{lat}) ) *
cos( radians ( vendors.latitude ) ) *
cos( radians( vendors.longitude ) - radians(#{lng}) ) +
sin( radians(#{lat}) ) * sin( radians( vendors.latitude ) ) ) )”
conditions = Hash.new
conditions[:select] = “#{Parent.quoted_table_name}.*,
#{distance_formula} AS distance”
p = Parent.scoped
p = Parent.includes(:child).where(“child.start_time <= :now and
child.expired_time > :now and (child.original_quantity -
child.brought_quantity > 0)”, {:now => Time.zone.now + 20.minutes})
results = p.all conditions

the above code will get me all the attribute from Parent and Child
object, but missing the calculated column that I wanted to added.

Am I missing something obvious? Or is there no way to do this?