簡體   English   中英

來自配置的 Rails 引擎 model inheritance

[英]Rails engine model inheritance from config

我有一個主機應用程序和引擎。 它們應該是獨立的並且有自己的模型。 但是,當我想在我的主機應用程序中包含引擎時,我希望能夠從主機應用程序繼承用戶。

所以我做了以下

module VotingApp
  class Engine < ::Rails::Engine
    isolate_namespace VotingApp

    config.user_model = VotingApp::ApplicationRecord
    config.user_model_path = nil

在主機應用程序的初始化程序中

  require 'voting_app'

  VotingApp::Engine.config.user_model = ::User
  VotingApp::Engine.config.user_model_path = Rails.root.join('app/models/user.rb')

最后是引擎的 model。

module VotingApp
  class User < VotingApp::Engine.config.user_model

但是,這似乎不起作用,因為VotingApp::Engine.config.user_model僅在VotingAp::User加載后設置為::User 有沒有辦法重新加載 class?

對於任何想知道的人,在這樣做之后,您需要

  1. 卸載當前 model 以便重新加載

  2. 重新加載 model

     VotingApp.send(:remove_const, :User) load "#{VotingApp::Engine.root}/app/models/voting_app/user.rb"

然后一切都按預期工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM