Rails,Puma,Postgres:预加载活动记录定义?

时间:2016-03-09 00:24:29

标签: ruby-on-rails postgresql activerecord puma

每次启动后,我都会在数据库中看到这样的查询:

enter image description here

一旦每个美洲狮工人被一个请求命中(击中数据库),这些就会消失。它很烦人,因为它可以为请求添加50多个sql查询(1​​s +)。我想做的就是每次工人上车时都会预先加载它们。

我已经尝试了

on_worker_boot do
  ActiveSupport.on_load(:active_record) do
    ActiveRecord::Base.establish_connection
  end
  Rails.application.eager_load!
  ::Rails::Engine.subclasses.map(&:instance).each { |engine| engine.eager_load! }
  ActiveRecord::Base.descendants
end

哪个不起作用。

我有两个

  config.cache_classes = true
  config.eager_load = true

在我的环境中设置。

我期待有某种类型的rails设置可以做到这一点 - 在生产中默认情况下似乎是明智的做法?

1 个答案:

答案 0 :(得分:1)

请参阅https://github.com/rails/rails/issues/24133

Rails 5将有改进,但您目前仍需要做:

# https://github.com/rails/rails/issues/24133
ActiveSupport.on_load(:active_record) do
  con = ActiveRecord::Base.connection
  filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump")

  con.schema_cache.clear!
  con.data_sources.each { |table| con.schema_cache.add(table) }
  open(filename, 'wb') { |f| f.write(Marshal.dump(con.schema_cache)) }
end

在初始化程序中。