Hopefully this will be simple. But I've hunted for a couple hours now and can't seem to get this to work. I have users who have multiple addresses, I'm trying to use Geocoder gem to display these users by a zip code search, my code is very similar to what is in the Geocoder Railscast.
Here's my controller attempt 1 and returns "undefined method `Addresses'"
def index
if params[:search].present?
@profiles = Profile.Addresses.near(params[:search], 25, :order => :distance)
@title = "Therapists Near " + :search
else
@profiles = Profile.all
@title = "Everyone"
end
end
This is attempt number 2, this returns "uninitialized constant ProfilesController::Addresses" (I don't know if the Profile.where bit will work, but its not even getting to that part...)
class ProfilesController < ApplicationController
def index
if params[:search].present?
addresses = Addresses.near(params[:search], 25, :order => :distance)
@profiles = Profile.where(:id => addresses.id)
@title = "Therapists Near " + :search
else
@profiles = Profile.all
@title = "Everyone"
end
end
Here's my models:
class Profile < ActiveRecord::Base
has_many :addresses, :dependent => :destroy
accepts_nested_attributes_for :addresses, :reject_if => lambda { |a| a[:street].blank? }, :allow_destroy => true
class Address < ActiveRecord::Base
belongs_to :profile
geocoded_by :street
after_validation :geocode, :if => :street_changed?
Thanks a lot for taking a look!
Additional, you may change to the following to get all profiles:
addresses = Address.near(params[:search], 25, :order => :distance)
@profiles = addresses.map{ |ad| ad.profile }.uniq unless addresses.nil?
If there are matched addresses, then find the profile from each address.