필요한 일치 패턴을 가진 사용자의 첫 번째 쿼리. 별도의 모델
user_pattern = "N"
users = User.where("name like ?", "%#{user_pattern}%")
다음 두 때문에 필요한 패턴
location_pattern = "NY"
locaations_array = users.includes(:locations).collect(&:locations).flatten // eager loading locations and converting them to 1D array.
locations = locations_array.select{ |location| location.name.casecmp("#{location_pattern}") == 0 } // this does a case ignore comparison
과 위치를 얻기를 위해 비슷한 쿼리를 사용하고, 그것은 모두 하나의 쿼리를 사용하여 얻을 어렵습니다. 그래서, 난 당신의 코드 중 일부가 작동하지 않습니다 위의
def users_with_locations(user_pattern, location_pattern)
result = Hash.new
users = User.where("name like ?", "%#{user_pattern}%")
locations_array = users.includes(:locations).collect(&:locations).flatten // I'm eager loading all the locations and converting them to a 1D array
locations = locations_array.select{ |location| location.name.casecmp(location_pattern) == 0 } // this does a case ignore comparison
result[:users] = users
result[:locations] = locations
result
end
의 모든 작업을 수행 할 결과
또는 간단한 방법을 프레임에 해시를 사용하고 있습니다. 'users.locations'에 대해'정의되지 않은 메소드 위치 '를 얻습니다. – Yonk
죄송합니다. 업데이트 된 코드로 테스트하고 확인해 주시겠습니까? –