Rails更改查询执行顺序

时间:2014-06-08 17:33:52

标签: sql ruby-on-rails activerecord ruby-on-rails-4

我想对前10条记录执行查询。

所以,从Rails控制台我输入:

Log.all.limit(10).where({"username"=>"peeyush"}).explain

这给出了:

Log Load (0.8ms)  SELECT  "logs".* FROM "logs"  WHERE "logs"."username" = 'peeyush' LIMIT 10

显然,LIMIT 10会在稍后发生。

我尝试跑步:

Log.all.first(10).where({"username"=>"peeyush"}).explain

但这会产生错误:

NoMethodError: undefined method `where' for #<Array:0x0000000539acd8>

如何执行查询?

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您想检索前10行,然后按用户名过滤这10条记录?

以红宝石过滤

all.first(10).find_all {|i| i.username == "peeyush" }

过滤数据库

all.where(:id => all.first(10).map {|x| x.id}, :username => "peeyush")