Rails 3 loading all models on startup

后端 未结 3 1415
情书的邮戳
情书的邮戳 2021-02-05 18:32

I have a class method mixed in to all my models. the method gets called when the model class is evaluated. unfortunately (for me), this seems to be on-demand, whenever the model

相关标签:
3条回答
  • 2021-02-05 18:54

    The correct way to do this application-wide is to turn on cache_classes in your configuration. By default it's off in development but on in production.

    If you want to do it sporadically:

    Rails.application.eager_load!
    
    0 讨论(0)
  • 2021-02-05 18:54

    In MVC concept models are not intended to act by themselves, i.e. they should only act when controller sends them a message (for example, @foo.register_acl). Model instances even should not exist until they are created by controller.

    What are you trying to achieve with your register_acl method?

    If you really need something to be executed on object creation you can use initialize() method which is called whenever a Ruby object is created.

    However if you need model to execute some code by itself you are most likely facing some code smell and you need to change something within your app.

    0 讨论(0)
  • 2021-02-05 19:02

    I dont know if this is ideal, but it works for me. Somewhere in the config/initialize/, i do this:

    Dir.glob("#{Rails.root}/app/models/*.rb").sort.each { |file| require_dependency file }
    

    and that preloads my models

    0 讨论(0)
提交回复
热议问题