Search code examples
ruby-on-railsrails-geocoder

Very weird result with geocoder has_many and belongs_to association


I am using Geocoder Gem, it is showing wired behavior.

I have Location model

class Location < ActiveRecord::Base
has_many :events
geocoded_by :address
after_validation :geocode
def full_address
    "#{postal_code}, #{city}, #{street}"
  end
end

and Event model

class Event < ActiveRecord::Base
    belongs_to :location
    accepts_nested_attributes_for :location
end

I want to find all events nearby the current user's location.

I tried following steps to find nearby locations..

nearby_loc = current_user_location.nearby

it is returning all nearby "locations" of current users location

Then I tried

nearby_loc.events

but it is giving me error

NoMethodError: undefined method `events' for #<ActiveRecord::Relation::ActiveRecord_Relation_Location:0x0000000958c088>

Please help me ...


Solution

  • The events is defined on a location, and nearby will give you a list of locations, so you will have to iterate over the list.

    Simply put:

    all_related_events  = []
    nearby_locations.includes(:events).each do |location|
      all_related_events += location.events
    end 
    

    It also helps if your variable names more correctly reflect what they contain, so use nearby_locations instead of nearby_loc.

    [UPDATE]

    To minimise the number of queries, I added the .includes(:events) which will fetch all events in one query.