Ruby-on-rails Rails 4,使用 ActiveRecord 的原始查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15855606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:46:14  来源:igfitidea点击:

Rails 4, raw query using ActiveRecord

ruby-on-railsruby

提问by randombits

Is there currently a way to do a raw SQL select query using ActiveRecord in Rails 4.0.0.beta1? I see ActiveRecord::Base.execute no longer exists. What's the correct way of going about this?

目前有没有办法在 Rails 4.0.0.beta1 中使用 ActiveRecord 进行原始 SQL 选择查询?我看到 ActiveRecord::Base.execute 不再存在。解决这个问题的正确方法是什么?

回答by ant

Here try this, select example.. :

在这里试试这个,选择示例..:

query = "select ...."
results = ActiveRecord::Base.connection.execute(query)

回答by Guillaume Roderick

Just to add my ten pence, a raw query using Model.connection.execute won't return an ActiveRecord model - it'll return a raw data set.

加上我的十便士,使用 Model.connection.execute 的原始查询不会返回 ActiveRecord 模型 - 它会返回原始数据集。

The following will return ActiveRecord models:

以下将返回 ActiveRecord 模型:

MyModel.find_by_sql(query)

edit: assuming of course that you're running a select.

编辑:当然假设您正在运行选择。

回答by fearless_fool

In Rails 4 (perhaps previous versions as well), if you're going with a custom query for speed, you can add a :skip_loggingargument to avoid writing to the log:

在 Rails 4(也许以前的版本也是如此)中,如果您要使用自定义查询来提高速度,您可以添加一个:skip_logging参数来避免写入日志:

query = "SELECT ..."
results = MyModel.connection.execute(query, :skip_logging)

(Note: If I'm reading the sources correctly, this might not hold true in PostgreSQL.)

(注意:如果我正确阅读了源代码,这在 PostgreSQL 中可能不成立。)