Search code examples
ruby-on-railsrubyweb-deploymentrails-geocoder

Geocoder near method with model associations


I'm trying to get the near method from geocoder gem working with a model that is associated with another model. I have 2 models restaurants and menus, menus belongs to restaurants. I have a form with a search method in each model, the near method works with my restaurants model

 def self.search_for(params)
      restaurants = Restaurant.where(category_id: params[:category].to_i)
      restaurants = restaurants.near(params[:location],2) if params[:location].present?
      restaurants
end

I'm searching for a restaurant near the user that sells a dish the user has entered, however the code gives a no method error (undefined method 'restaurants')

def self.search_for_menus(params)

    menus=Menu.where("dish LIKE ?", "%#{params[:dish]}%") if params[:dish].present?
    menus= menus.restaurants.near(params[:location],2) if params[:location].present?
   menus
  end

In my console I am able to do m=Menu.find(11) then m.restaurant which returns that restaurant object and can further do m.restaurant.address which gives the address for geocoder near method to work, so I'm not sure how to go about fixing this.

Edited Code:

 def self.search_for_menus(params)

    menus=Menu.where("dish LIKE ?", "%#{params[:dish]}%") if params[:dish].present?
    rest_menu = []
    menus.each do |menu|
    rest_menu << menu.restaurant.nearbys(params[:location],2) if params[:location].present?

    end


   rest_menu

  end

Solution

  • Found a solution, it requires a join on the parent model and a reverse geocode

     reverse_geocoded_by "restaurants.latitude", "restaurants.longitude"
    
      def self.search_for_menus(params)
    
        menus=Menu.where("dish LIKE ?", "%#{params[:dish]}%") if params[:dish].present?
        menus= menus.joins(:restaurant).near(params[:location],2)
    
       menus
    
      end