1

我对活动记录有点困惑,它似乎在你停止的任何时候都会触发查询,即。

@model.where( :store_id => @sid )

这很好,但是如果我想构建这样的查询怎么办:

query = @model.where( :store_id => @sid )

if(some_condition)
  query.offset(50)

然后执行查询(实际上不是我在做什么,而是一个非常简单的例子)。有没有办法将查询按步骤组合起来,然后告诉它执行?

4

2 回答 2

3

实际上,ActiveRecord 会做你想要的。这称为延迟加载。您可能会对 rails 控制台感到困惑,它会在后台调用.inspect线路结果。

看看这个问题:Lazy loading in Rails 3.2.6

于 2013-09-20T23:33:09.167 回答
2

这已经像你想要的那样工作了。

where()返回 的实例ActiveRecord::Relation

该关系在需要之前不会执行它的数据库调用。您可能会遇到其他情况的原因是您正在控制台中对其进行测试,该控制台会打印每个语句的输出(从而加载关系)。loaded()您可以通过该方法测试是否已加载关系。

在控制台上试试这个:

m = @model.where(:store_id => @sid); # the semicolon will silence the output

m.loaded?  # nil
m          # executes db call, will print out the contents of the relation
m.loaded?  # true
于 2013-09-20T23:33:00.530 回答