我需要从数据库中查询大量数据。当我执行以下操作时,Heroku会超时,因为有30秒的限制:
account.records.all.each do |record|
record.contacts.all.each do |contact|
contact.address.all.each do |address|
..write to file etc
end
end
end
我已经读过SQL View将有助于提高性能,而不是查询.each()中的每条记录,但是我需要对这组数据执行where子句。目前,如果我使用' ExportAllRecord'像这样查看:ExportAllRecords.where(" account_id = 3"),它执行以下操作:
ExportAllRecord Load (5.0ms) SELECT "export_all_records".* FROM "export_all_records" WHERE (account_id = 3)
然而,我实际上需要它来添加' where子句'观点。
如何参数化SQL视图?
我正在使用ActiveRecord。
感谢。
答案 0 :(得分:0)
ActiveRecord
无关心从普通数据库表或数据库视图查询的位置。
假设您的数据库视图名为export_all_records
,那么只需创建一个新模型:
# in app/model/export_all_record.rb
class ExportAllRecord < ActiveRecord::Base
default_scope { readonly }
end
像普通ActiveRecord
模型一样使用此模型:
id = 3 # or perhaps params[:id]
ExportAllRecord.find_by(account_id: id)
#=> returns all records from the view with the given id
如果您需要,可以添加更多条件:
ExportAllRecord.
where(account_id: id).
where(column1: true, column2: 'foobar')
order(:column3)