Host app and engine with same model name, rendering host app's model from inside engine using host app's partial, rails

时间:2015-06-15 14:42:01

标签: ruby-on-rails ruby rails-engines

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.

What I am trying to do is this: From inside the engine, I want to find all of host app's articles and then render them.

#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 and I don't know why
    end
    ...
  end
end 

And then the view:

#views/blorgh/articles/index.html.erb
<p> Here I will render blorg's articles </p>
<%= render @articles %>

<p> Here I want to render the host app's articles </p>
<%= render main_app.@host_app_articles%>

So two problems going on:

  1. I can't seem to grab the host app's articles from inside the engine
  2. Even if I did grab the host app's articles from inside the engine, I do not know how to render the host app's articles using the host app's partial: _article.rb. In a normal app I would just do render @host_app_articles but since the view lives in the host app, I figured I would do render main_app.@host_app_articles but I don't think that works.

1 个答案:

答案 0 :(得分:0)

从引擎中抓取主持人的文章:

@host_app_articles = ::Article.all  #refers to top-level namespace class

从引擎内的视图中渲染它:

<% @host_articles.each do |article| %>
  <%= render file: "/app/views/articles/_article", locals: {article: article} %>
<% end %>

只是为了完成,以下是主机应用程序中的部分内容:

#unicorn/app/views/articles/_article.rb
<%= article.title %> <br> <%= article.text %>