3

What is the proper way of defining indexes on associated models with following configuration?

I have model Locality with lat and lng attributes and associated models Profile and User

class User < ActiveRecord::Base
  has_one :user_profile

  define_index do
    # This doesn't work :(
    has "RADIANS(user_profiles.localities.lat)", :as => :lat, :type => :float
    has "RADIANS(user_profiles.localities.lng)", :as => :lng, :type => :float
  end
end

end

class UserProfile < ActiveRecord::Base
  belongs_to :user
  belongs_to :locality
end

class Locality < ActiveRecord::Base
  has_many :user_profiles
end

I need to define indexes for User model so I can perform geo-searches on it.

Thank you for the answers!

Igor Pavelek
  • 1,444
  • 14
  • 22

2 Answers2

10

The problem is twofold:

  • Thinking Sphinx doesn't know that you want to join the user_profile and locality associations.
  • SQL snippets should be just that - standard SQL - so you can't chain associations within them.

The following should do the trick:

define_index do
  # force the join on the associations
  join user_profile.locality

  # normal SQL:
  has "RADIANS(localities.lat)", :as => :lat, :type => :float
  has "RADIANS(localities.lng)", :as => :lng, :type => :float
end

Claudio's point of using singular references within the SQL is not correct - within SQL, you want table names. But you do want the correct association references in the join call (hence they're singular there).

Cheers

pat
  • 16,116
  • 5
  • 40
  • 46
1

Don't really know the exact solution but:

You have a typo:

has_one :user_profile

define_index do
    # This doesn't work :(
    has "RADIANS(user_profiles.localities.lat)", :as => :lat, :type => :float

You are using "user_profiles" for the attribute, it should not be plural, try changing it to: "user_profile".

I repeat, I don't know if you can navigate through associations for this case, but if you can, this should be a typo.

You can read here for more information: http://freelancing-god.github.com/ts/en/geosearching.html

Claudio Acciaresi
  • 31,951
  • 5
  • 33
  • 43