0
是否可以使用pg_search來查詢具有多個位置但僅返回用戶和匹配關聯對象的用戶?因此,如果用戶有兩個來自紐約的地點,另一個用戶在紐約和佛羅里達有地點。我們可以做User.search_name_and_location('F NY')
,並用名字中的F取回與F匹配的所有人,並且與NY相匹配的相關對象?通過名稱和關聯位置查詢用戶,但只返回用戶匹配的位置不是所有位置
是否可以使用pg_search來查詢具有多個位置但僅返回用戶和匹配關聯對象的用戶?因此,如果用戶有兩個來自紐約的地點,另一個用戶在紐約和佛羅里達有地點。我們可以做User.search_name_and_location('F NY')
,並用名字中的F取回與F匹配的所有人,並且與NY相匹配的相關對象?通過名稱和關聯位置查詢用戶,但只返回用戶匹配的位置不是所有位置
首先查詢具有所需匹配模式的用戶。
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
一些代碼不工作的。我爲'users.locations'獲得'未定義的方法位置'。 – Yonk
對不起。你可以請測試與更新的代碼並確認。 –