1

I have the following model associations:

A concert has_one location. Location is a polymorphic association (concerts are not the only locatables). The location is geocoded through its address attribute by the geocoder gem.

The goal is to find a concert near a certain city that will take place in the future. While the geocoder gem provides the .near(address_string) method to find a record by an address, I can only apply that method to the location class, not to the concert class.

I have come up with the following workaround:

Location.near("Berlin").where(locatable_type: 'Concert').map(&:locatable)

Let me break this down:

Location.near("Berlin")
# ==> returns locations of any kind near Berlin

.where(locatable_type: 'Concert')
# ==> returns concert locations near Berlin

.map(&:locatable)
# ==> returns an array of concerts near Berlin

The problem is that this returns an array of concerts, but I would prefer a relation so that I can use my upcoming concert scope to find only concerts that take place in the future.

Any ideas on how to do that?

Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115

1 Answers1

1

You can have ActiveRecord::Relation doing this:

locatable_ids = Location.near('Berlin').where(locatable_type: 'Concert').map(&:locatable_id)
@concerts = Concert.where(id: locatable_ids).upcoming
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91