Rails活动记录查询

时间:2011-11-04 19:07:54

标签: ruby-on-rails ruby sqlite

我将如何进行这样的查询。 我有

@model = Model.near([latitude, longitude], 6.8)

现在我想过滤另一个模型,它与上面的模型相关联。  (帮助我找到正确的方法)

model2 = Model2.where("model_id == :one_of_the_models_filtered_above", {:one_of_the_models_filtered_above => only_from_the_models_filtered_above})

model.rb就像这样

has_many :model2s

model2.rb

belongs_to :model

现在就是这样(在@model = Model.near之后([纬度,经度],6.8)

model2s =[]
models.each do |model|
   model.model2s.each do |model2|
      model2.push(model2)
   end
end

我想完成同样的事情,但是使用有效的记录查询

我想我找到了一些东西,为什么会失败

Model2.where("model.distance_from([:latitude,:longitude]) < :dist", {:latitude => latitude, :longitude => longitude, :dist => 6.8})

此查询会抛出此错误

SQLite3::SQLException: near "(": syntax error: SELECT "tags".* FROM "tags"  WHERE (model.distance_from([43.45101666666667,-80.49773333333333]) < 6.8)

,为什么

1 个答案:

答案 0 :(得分:0)

使用includes。它会急切加载相关的模型(只有两个SQL查询而不是N + 1)。

@models = Model.near( [latitude, longitude], 6.8 ).includes( :model2s )

所以,当您执行@models.first.model2s时,已经加载了关联的模型2(有关详细信息,请参阅RoR guides)。

如果您想获得属于您的模型集合的所有model2的数组,您可以这样做:

@models.collect( &:model2s ) 
# add .flatten at the end of the chain if you want a one level deep array
# add .uniq at the end of the chain if you don't want duplicates

collect(也称为map)将在数组中收集传递给每个调用者元素的任何块的结果(这与您的代码完全相同,请参阅Enumerable's doc了解更多信息)。符号前面的&将其转换为传递给集合中每个元素的Proc,因此这与写入相同

@models.collect {|model| model.model2s }

还有一件事:@mu是对的,似乎SQLite不知道你的distance_from存储过程。由于我怀疑这是一个与GIS相关的问题,您可以在gis.stackexchange.com

上询问此特定问题
相关问题