2017-01-03 46 views

回答

1

首先查詢具有所需匹配模式的用戶。

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 

由於兩者都是獨立的模型,這是很難既使用單個查詢來獲取。所以,我使用的哈希幀結果

result = Hash.new(users: users, locations: locations) 
result[:users] = users 
result[:locations] = locations 

或一個簡單的方法來做到以上

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 
+0

一些代碼不工作的。我爲'users.locations'獲得'未定義的方法位置'。 – Yonk

+0

對不起。你可以請測試與更新的代碼並確認。 –