0

I have the following query

@initial_matches = Listing.find_by_sql(["SELECT * FROM listings WHERE industry = ?", current_user.industry])

Is there a way I can run another SQL query on the selection from the above query using a each do? I want to run geokit calculations to eliminate certain listings that are outside of a specified distance...

2 Answers 2

1

Your question is slightly confusing. Do you want to use each..do (ruby) to do the filtering. Or do you want to use a sql query. Here is how you can let the ruby process do the filtering

refined list = @initial_matches.map { |listing|
   listing.out_of_bounds? ? nil : listing
}.comact 

If you wanted to use sql you could simply add additional sql (maybe a sub-select) it into your Listing.find_by_sql call.

If you want to do as you say in your comment.

WHERE location1.distance_from(location2, :units=>:miles)

You are mixing ruby (location1.distance_from(location2, :units=>:miles)) and sql (WHERE X > 50). This is difficult, but not impossible.

However, if you have to do the distance calculation in ruby already, why not do the filtering there as well. So in the spirit of my first example.

listing2 = some_location_to_filter_by
@refined_list = @initial_matches.map { |listing|
   listing.distance_from(listing2) > 50 ? nil : listing
}.compact 

This will iterate over all listings, keeping only those that are further than 50 from some predetermined listing.

EDIT: If this logic is done in the controller you need to assign to @refined_list instead of refined_list since only controller instance variables (as opposed to local ones) are accessible to the view.

Sign up to request clarification or add additional context in comments.

5 Comments

My problem is, I need to do this: WHERE location1.distance_from(location2, :units=>:miles) < 50 and I obviously can't do that in SQL because distance_from is a ruby function
Ha sorry - hit enter by accident.
see my edit. however some more specificity, would still go a long way. What is location1 and location2 in reference to your original post?
Quick question -- in my view, when I go to print out items - to I refer to refined_list or back to @initial_matches? I keep getting errors, not sure how to print these out. Also did you mean .compact?
I did compact and you should refer to @refined_list. See my edit.
0

In short, no. This is because after the initial query, you are not left with a relational table or view, you are left with an array of activerecord objects. So any processing to be done after the initial query has to be in the format of ruby and activerecord, not sql.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.