rails 关联模型
Here’s the scenario:
这是场景:
You’re using the
rails_admin
gem in your Rails ~6 project您正在
rails_admin
项目中使用rails_admin
gemYou’re configuring your models for
rails_admin
via concerns, or placing your configuration directly on the model.您正在通过担忧为
rails_admin
配置模型,或者将配置直接放在模型上。You don’t want to have to restart your server every time you make a change to your model config (or general
rails_admin
config)您不需要每次更改模型配置(或常规
rails_admin
配置)时都必须重新启动服务器。
To give an example of the second point, here’s an example model group.rb and it’s related admin concern concerns/moderate/group_config.rb
为了说明第二点,这里是一个示例模型group.rb及其相关的管理员关注问题/moderate/group_config.rb
This configuration works as intended, however any subsequent changes to GroupConfig
will require the server to be restarted. If you’re working with Docker & VSCode this is an absolute pain, not to mention how larger projects can result in slower boot times in general.
此配置按预期工作,但是对GroupConfig
任何后续更改都将需要重新启动服务器。 如果您使用的是Docker&VSCode,这是绝对的痛苦,更不用说更大的项目通常会导致启动时间变慢。
The fix? Some rails magic at the ApplicationController
level
解决办法? 在ApplicationController
级别上有一些魔力
第一步:配置父控制器 (Step One: Configure a Parent Controller)
This can technically be done using the default parent controller, but for simplicity & readability I recommend using the ApplicationController
:
从技术上讲,这可以使用默认的父控制器来完成,但是为简单起见,我建议使用ApplicationController
:
第二步:定义重载机制 (Step Two: Define a Reload Mechanism)
In order to dynamically reload configurations, we need to call a method on each request that routes to the rails_admin
controller:
为了动态地重新加载配置,我们需要在路由到rails_admin
控制器的每个请求上调用一个方法:
第三步:定义重新加载方法 (Step Three: Define the Reload Method)
Because we have configuration within our models, we can’t just reload the initialize alone. To work around this we remove the model definition first and load the model definition again.
因为我们在模型中具有配置,所以我们不能仅重新加载初始化。 要解决此问题,我们首先删除模型定义,然后再次加载模型定义。
完成,完成 (Done, Done)
That’s it! Each time you reload your application, Rails will now reload your rails_admin
configurations if the requested route is directed to the rails_admin controller.
而已! 每次您重新加载应用程序时,如果将请求的路由定向到rails_admin控制器,Rails现在都会重新加载rails_admin
配置。
Here’s a gist if you’d like to see the final state of the ApplicationController
in this example:
如果您想在此示例中查看ApplicationController
的最终状态,这是一个要点 :
rails 关联模型