[英]Activerecord query with array in where clause
我的Rails应用程序中有一个位置表,该表有四列:-
| ID | 经度| 纬度| 用户身份
现在,我有一个包含user_ids列表的数组。 如何编写活动记录查询以选择每个用户ID的最后一行。 例如,如果我的数组[1,2,3]中有3个user_id,则我希望查询仅返回表中与每个user_id对应的最后一行(假定表中存在每个user_id的条目)。
因此,到目前为止,我可以使用以下查询获取与所有user_ids对应的所有行:
@ids = [1,2,3]
@locations = Location.where(user_id: ids)
如何修改此activerecord查询,使其仅返回与每个user_id对应的最后一行
假设您的User
模型具有许多位置,则可以从用户模型开始,并使用关联关系来获取每个用户的最后位置。
User.where(:id => @ids).includes(:locations).collect { |u| u.locations.last }
User.where(:id => @ids)
返回您的用户对象集合。 includes(:locations)
渴望加载相关的位置,因此我们不会遇到n+1
问题。 collect { |u| u.locations.last }
collect { |u| u.locations.last }
将最后关联的位置映射到数组中 您也可以尝试以下操作:
@ids = [1,2,3]
@locations = @ids.map {|id| [Location.where(user_id: id).last.location,User.find(id).name]}
#This would give you something like this: [["US",XYZ],["IND","ABC"]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.