如何基于已排序的Location结果查询关联的Store数据?
正确实现方式
你的初步写法问题在于,location.store_id只能获取单个Location对象的关联store_id,而你现在拥有的是一个Location集合,需要先提取所有Location的store_id组成数组,再传入查询。
方法1:基础查询(不保持原Location顺序)
先提取所有store_id,再查询对应的Store:
# 从locations集合中提取所有store_id,返回数组 store_ids = locations.pluck(:store_id) # 根据store_id数组查询Store stores = Store.where(id: store_ids)
这种方式会返回所有匹配的Store记录,但默认按Store的id排序,不会保持原locations的顺序。
方法2:保持原Location的顺序查询
如果需要Store的顺序和原locations的顺序一致(比如你之前对Location做了排序,希望Store也对应这个顺序),可以根据数据库类型调整排序逻辑:
MySQL 数据库:
store_ids = locations.pluck(:store_id) stores = Store.where(id: store_ids).order("FIELD(id, #{store_ids.join(',')})")
PostgreSQL 数据库:
store_ids = locations.pluck(:store_id) stores = Store.where(id: store_ids).order(Arel.sql("array_position(ARRAY[#{store_ids.join(',')}], id)"))
方法3:利用模型关联(简洁写法)
如果你的Location模型已经定义了关联:
# app/models/location.rb class Location < ApplicationRecord belongs_to :store end
可以直接通过关联加载Store,并自动去重:
stores = locations.includes(:store).map(&:store).uniq
这种写法更简洁,且会保持原locations的顺序,适合场景简单的情况。
内容的提问来源于stack exchange,提问作者Rodrigo Ladrón de Guevara
相关产品推荐
相关产品推荐

