Model Association issue in Rails
-
28-10-2019 - |
Question
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!
Solution
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.
OTHER TIPS
For number 2, you have to change from Addresses.near(params[:search], 25, :order => :distance)
to Address.near(params[:search], 25, :order => :distance)
.
I found i couldn't paginate with the accepted answer. So I got pretty grubby:
addresses = Address.near(params[:search], 25, :order => :distance)
locations_id_array = []
addresses.each do |address|
addresses_id_array << address.id
end
@profiles = Profile.where(:address_id => addresses_id_array).paginate(:page => params[:page], :per_page => 5).order('name DESC')
If anyone has a nicer, scaleable way to do this (preferably with scopes) I'd love to hear it.