Q: Is there a clean way to merge ActiveRecord::Relation results?
cdesch opened this issue · comments
I am returning a series of ActiveRecord::Relations from the GeoKit-Rails method in_range. I want to combine each of these so they can returned as one array of objects in a controller action.
code:
def find_panels_within_radius_of_poi(min_range, max_range, points_of_interest)
panels = Array.new
points_of_interest.each do |poi_id|
poi = PointOfInterest.find(poi_id)
panels << Panel.in_range(min_range..max_range, :origin => poi.origin)
end
panels.each do |panel|
puts panel
end
panels
end
The current code gives me an array of ActiveRecord::Relations like this :
[#<ActiveRecord::Relation []>, #<ActiveRecord::Relation []>, #<ActiveRecord::Relation [#<Panel id: "00c077c8-047d-4cd7-8c24-5ca96f5bf9fa", geopath_panel_id: nil, plant_unit_id: "1307", structure_id: nil,....
How can I combine these? I know there is a ActiveRecord::Relation Merge method, but it would look very messy to have the first item retrieved then having subsequent items merged into it. Is there a way to do it functionally, like how I might do it with Elixir's Reduce Method.
Hi,
I didn't try with ActiveRecord::Relation object but have you tried flatten
method in ruby?
Example usage: https://stackoverflow.com/questions/35736060/ruby-array-flatten
If you still need to do this, your best bet is to use pluck and pluck the IDs. Model.in_range(min_range..max_range, origin: x).pluck(:id)
And union each array of IDs with | and then at the end perform a query to find all records with those IDs Model.where("ID in (?)", ids)