我有以下联想
class Location < ActiveRecord::Base
has_many :items
end
class Item < ActiveRecord::Base
belongs_to :location
end
假设我有一些 Location 实例,我要查询属于这些位置的所有项目。目前我设法以数组的形式得到结果
items =[]
Location.near(latitude,longitude,distance).find_each do |location|
location.items.find_each do |item|
items << item
end
end
但是,有什么办法可以将结果作为 ActiveRecord::Relation.因为我想通过使用“where”和 ActiveRecord::Relation 来进一步查询结果。
附言“near”方法来自geocoder gem,它返回一个ActiveRecord::Relation。
--------------------编辑------------------------ ---
谢谢你的回复我几乎找到了解决方案
locations = Location.near(latitude,longitude,distance)
Item.where(location_id: locations.pluck(:id))
这是正确的做法吗?对我来说这有点不直观。
--------------------再次编辑-------------------- ----
只是一个小评论:我说这是不直观的,因为我正在从 DataMapper 切换。如果是Datamapper就很简单了,像
Location.near(blabla).items
通过关联进行查询非常简单。与Datamapper相比,无法理解为什么ActiveRecord关联如此无用?
最佳答案
编辑以使用一个带有映射的查询...
billy 上面说的,但另一种可能更快的选择:
locations = Location.near(1, 2, 3)
items = Item.where(:location_id => locations.map(&:ids)
关于ruby-on-rails - rails,如何合并两个 ActiveRecord 查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17977608/