如何在Heroku上预编译资产时普遍跳过数据库触摸

jas*_*ber 33 database ruby-on-rails heroku asset-pipeline

我正在向Heroku的Cedar堆栈部署一个Rails 3.1应用程序.使用Heroku Cedar和Rails 3.1,您可以在本地自己编译资源,让Heroku在推送时(在"slug编译"期间)编译它们,或者在应用程序运行时及时编译它们.我想做中间选项,让Heroku预编译资产.

当Heroku运行资产:预编译任务时,它会因"无法连接到服务器"而出错,因为应用程序正在尝试连接到数据库但在slug编译阶段没有可用的数据库.此时缺乏数据库连接是预期的,也是不可避免的.我正在寻找一种方法来超越它,因为数据库连接对资产预编译并不重要.

我的应用程序试图连接到数据库的部分是Devise.devise_for :users在routes.rb中有一行想要查看用户模型.

我可以编写一个rake任务来存储devise_for并使其成为资产的先决条件:预编译.我认为这可以解决我的问题,但我正在寻找一个更通用的解决方案,我可以在任何 Rails 3.1应用程序上使用Heroku上的这个问题.

那里有什么东西,或者你能想到任何能够在运行应用程序足以产生路由和资产路径的同时消除数据库连接错误的东西吗?

显然,如果一个应用程序需要在启动期间读/写数据,我们不能存根,但我们可以自动伪造每个ActiveRecord模型吗?

fri*_*ngd 46

将此添加到config/application.rb

config.assets.initialize_on_precompile=false                                                  
Run Code Online (Sandbox Code Playgroud)

我花了一段时间来追捕它...将它添加到config/environments/*.rb不起作用

更新:它不适用于rails 4

  • 官方Rails指南中也引用了有关资产管道的内容:http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets (3认同)

kch*_*kch 13

Heroku现在提供了一个labs标志,可以在编译期间使运行时环境可用,这意味着您的应用程序将能够成功连接到您的DATABASE_URL数据库.

首先,您需要安装labs插件:

$ heroku plugins:install http://github.com/heroku/heroku-labs.git
Run Code Online (Sandbox Code Playgroud)

然后启用user-env-compile实验室功能:

$ heroku labs:enable user-env-compile --app your-app-name
Run Code Online (Sandbox Code Playgroud)


fph*_*ipe 5

对我来说问题是activerecord instantiate_observer在调用lib/active_record/railtie.rb:92.这将加载观察者和相应的模型.has_and_belongs_to_many然后连接到数据库.

我想我会在ENV["RAILS_ASSETS_PRECOMPILE"]存在时覆盖此方法,该方法由布拉德利链接到的修正版中的设计使用.

编辑:所以这段代码为我修好了:

namespace :assets do
  # Prepend the assets:precompile_prepare task to assets:precompile.
  task :precompile => :precompile_prepare

  # This task will be called before assets:precompile to optimize the
  # compilation, i.e. to prevent any DB calls.
  task 'precompile_prepare' do
    # Without this assets:precompile will call itself again with this var set.
    # This basically speeds things up.
    ENV['RAILS_GROUPS'] = 'assets'

    # Devise uses this flag to prevent connecting to the db.
    ENV['RAILS_ASSETS_PRECOMPILE'] = 'true'

    # Prevent loading observers which will load the models which in turn may hit
    # the DB.
    module ActiveModel::Observing::ClassMethods
      def instantiate_observers; end
    end

    # Prevent route drawing because certain gems might get called which will hit
    # the DB.
    class ActionDispatch::Routing::RouteSet
      def draw; end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)


Bra*_*est 3

编辑:这个答案已经过时,不再有效 - 请参阅 fringd 的答案。

不完全是通用存根,但设计现在添加了一个检查来解决这个特定问题。在 Github 上查看问题修复。通过提供 RAILS_ASSETS_PRECOMPILE 环境配置设备应该跳过构建路由

  • 抱歉,我认为这个修复实际上已经从 Devise 和 Rails 中撤回,Jose Valim 做了一些花哨的步法来尝试解决这个问题,但我认为他认为这不是他们可以做太多的事情时间点。如果 Devise HEAD 和 Rails 3-1-stable 分支仍然出现问题,恐怕我认为除了研究您的设计模型并尝试找出导致问题的特定方法之外,没有其他可做的了。 (2认同)