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
对不起。你可以请测试与更新的代码并确认。 –