【问题标题】:Rails query portion of model模型的 Rails 查询部分
【发布时间】:2011-11-04 13:41:21
【问题描述】:

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

@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

我在轨道 3 上

现在是这样的(@model = Model.near([latitude, longitude], 6.8)之后)

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

我想完成同样的事情,但要使用活动记录查询

我部分找到了我的问题的答案。它仍然包含我不满意的旧方法。

models.each do |model|
   models-model2s = Model2.where("model_id => :modid",{:modid => model.id})
   model2 += model
end

但这是一种愚蠢的方法,玩弄 tadman 的方法让我知道 model.model2s 是我可以执行的命令(我忘记了),所以

models.each do |model|
   model2s += model.model2s
end

这并不完全是我想要的,但我一直在使用它,直到我看到更好的东西。 (我还在想tadman的逆向方法)

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

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)

,为什么

【问题讨论】:

  • 抱歉——第二行代码到底应该做什么?我无法理解。
  • @Nick 编辑了上面的问题,再看一遍
  • @Nick 检查我更新的问题

标签: ruby-on-rails ruby activerecord model


【解决方案1】:

间接检索第二种类型的模型可能会有一些运气:

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

这将预加载所有“model2s”。

或者您可以尝试翻转它并直接检索 Model2,但您必须能够以其他方式表达 near 条件:

@model2s = Model2.includes(:model).where('models.x' => ...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    相关资源
    最近更新 更多