简体   繁体   English

如何将原始 SQL 附加到现有的 Rails ActiveRecord 链?

[英]How to attach raw SQL to an existing Rails ActiveRecord chain?

I have a rule builder that ultimately builds up ActiveRecord queries by chaining multiple where calls, like so:我有一个规则构建器,它最终通过链接多个where调用来构建 ActiveRecord 查询,如下所示:

Track.where("tracks.popularity < ?", 1).where("(audio_features ->> 'valence')::numeric between ? and ?", 2, 5)

Then, if someone wants to sort the results randomly, it would append order("random()") .然后,如果有人想对结果进行随机排序,它会附加order("random()")

However, given the table size, random() is extremely inefficient for ordering, so I need to use Postgres TABLESAMPLE-ing.但是,考虑到表的大小, random()的排序效率极低,因此我需要使用 Postgres TABLESAMPLE-ing。

In a raw SQL query, that looks like this:在原始 SQL 查询中,如下所示:

SELECT * FROM "tracks" TABLESAMPLE SYSTEM(0.1) LIMIT 250;

Is there some way to add that TABLESAMPLE SYSTEM(0.1) to the existing chain of ActiveRecord calls?有什么方法可以将该TABLESAMPLE SYSTEM(0.1)到现有的 ActiveRecord 调用链中? Putting it inside a where() or order() doesn't work since it's not a WHERE or ORDER BY function.将它放在where()order()中不起作用,因为它不是 WHERE 或 ORDER BY 函数。

irb(main):004:0> Track.from('"tracks" TABLESAMPLE SYSTEM(0.1)')
  Track Load (0.7ms)  SELECT "tracks".* FROM "tracks" TABLESAMPLE SYSTEM(0.1) LIMIT $1  [["LIMIT", 11]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM