2014-09-21 3 views
0

레일 4.1에서 지오 코더 젬을 사용하고 다음 모델을 설정하십시오. 코드는 작동하지만 글 머리 기호 젬은이 줄을 감지합니다. places.select {| place | @ countries.places.include? (place.country)}을 N + 1 쿼리로 사용합니다. 열망하는로드를 통해 그것을 작성하는 좋은 방법은 있습니까? 요령은 지오 코더 메서드 에 의해 반환 된 위치 만 포함하는 국가 집합을 부근으로 반환하려는 것입니다.다음을 Rails 4.1에서 열심히로드 된 쿼리로 작성하는 방법은 무엇입니까?

모델 설정에서

class Country < ActiveRecord::Base 
    has_many :places 
end 

class Place < ActiveRecord::Base 
    has_one :country 
end 

some_controller.rb

@countries = Country.all 
places = Place.near(some_latitude_longitude_coordinates, 5500) 
places.select { |place| @countries.places.include?(place.country) } 

EDIT : some_controller.rb 하나 개 보정 - 읽어야

places.select { |place| @countries.include?(place.country) } 

바와 같이 통신에서 아래에있는 Country.all은 코드를 더 쉽게 읽을 수있는 자리 표시 자입니다. 실제로 @countries는 "모든 공산주의 국가"와 같은 속성을 가진 국가의 일부 (Country.all과 반대)입니다. 따라서, 나는 "모든 공산주의 국가들"과 같은 일부 재산을 가진 국가들과 좌표들의 집합과 국가들의 교차점을 찾고 싶다.

+0

'@ countries.places.include? (place.country)'무엇을 하는가? –

+0

안녕하세요 테이머, 오타되었습니다 - 위의 편집을 만들었습니다. 기본적으로 모든 국가 집합과 일부 좌표 부근에서 발견 된 장소 국가 간의 교차 지점입니다. @countries는 "모든 공산주의 국가"와 같은 일부 속성을 가진 국가의 실제 하위 집합입니다 (Country.all과 반대). – Nona

+0

아래 내 대답을 확인하십시오. –

답변

0

그것을 시도하지 않은 그러나 그것은 작동합니다 :

@countries = Country.all 
places = Place.includes(:country).near(some_latitude_longitude_coordinates, 5500) 
places.select { |place| @countries.include?(place.country) } 

이는 그 국가 @countries 콜렉션에 포함되어 장소 얻을 것이다.

0

적절한 열의 레코드를로드하려면 하나의 쿼리를 만들어야합니다. 나는 다음을 제안 할 것이다 :

@places = Place.near(some_latitude_longitude_coordinates, 5500).joins(:country).where(country_id: @countries.map(&:id))