简体   繁体   中英

Grab host app active record objects when engine and host app have same model names

I have a host app unicorn with the model Article .

I also have a mountable engine hooked into the host app called blorgh . It also has a model: Article . It is namespaced, so the table name for the engine's Article is actually blorgh_articles .

While inside the engine I want to grab the host app's article , not the engine's article . Is this possible?

#blorgh/app/controllers/blorgh/articles_controller.rb
require_dependency "blorgh_application_controller"
module Blorgh
  class ArticlesController < ApplicationController
    def index
      @articles = Article.all #properly grabs all the engine's articles
      @host_app_articles = main_app.Article.all # this doesn't work. It should grab the host app's articles.
    end
    ...
  end
end

Use ::Article to refer to the top-level namespace class, and MyEngine::Article to refer to the engine's class.

While using Article alone within the MyEngine namespace will resolve correctly, doing this introduces a couple of pitfalls:

  • It makes it confusing to understand your code as there are multiple references to an ambiguous Article .
  • If you ever rename your MyEngine::Article class to something else, but miss a reference to Article during this change, the same code will now change in meaning to refer to the global ::Article . This may or may not break your specs, and it may introduce unintended behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM