4

I've a bunch or addresses which belong to various other resources via polymorphic association

belongs_to :addressable, :polymorphic => true

and my resource, lets say its a Hotel

has_one :address, :as => :addressable

I can search my address data no problem, find every address in a 20 mile radius of my search string for example

@addresses = Address.near(params[:search],20, :order => :distance).page params[:page]

I'm really struggling to join the resource i.e. the hotel info, I can link through to a details page, but I'd like to show the name of the hotel in my results for example.

I thought using :include may have helped thus:

@addresses = Address.near(params[:search],20, :order => :distance, :include => :hotel).page params[:page]

.. but no luck

Any advice greatly appreciated.

Stew

stew
  • 275
  • 2
  • 10

2 Answers2

5

OK I figured it out with a little help from a colleague

 @addresses = Address.where(addressable_type: 'Hotel').near(params[:search],20, :order => :distance).includes(:addressable).page params[:page]

Hope it might help someone else!

stew
  • 275
  • 2
  • 10
  • Congrats on the solution. When you are able, please make sure to mark your answer as 'accepted' so that others might learn from you success. Cheers~ – Andrew Kozak Dec 21 '11 at 18:38
0

In your Address model, I would define the relation with the Hotel model

belongs_to :addressable, :polymorphic => true
belongs_to :hotel, -> { where(adresses: {addressable_type: 'Hotel'}) }, foreign_key: 'addressable_id'

Like well explained in this answer, Eager load polymorphic

Then, like explained in the geocoder doc https://github.com/alexreisner/geocoder#known-issue I would find hotels by location doing the following:

Address.near(generic_address, radius, :select => "addresses.*, hotels.*").joins(:hotel)
Community
  • 1
  • 1
edap
  • 1,084
  • 1
  • 10
  • 16