在rails引擎之间共享路由问题

时间:2014-02-11 22:26:20

标签: ruby-on-rails-4 routing nested-forms rails-engines

我有两种不同的隔离式可安装导轨发动机;一个名为Core,另一个名为Finance;

核心引擎有一个评论资源和路由问题,如;

Core::Engine.routes.draw do

  concern :commentable do
    resources :comments
  end

end

财务引擎有发票模型;

Finance::Engine.routes.draw do

  resources :invoices, concerns: :commentable

end

这两个引擎都添加了主应用程序的Gemfile和routes.rb文件,如下所示; 的Gemfile;

gem 'core', path: "../core"
gem 'finance', path: "../finance"

routes.rb中;

mount Core::Engine, at: "/"
mount Finance::Engine, at: "/"

在金融宝石;发票show.erb的评论表如下;

<%= form_for [@invoice, @comment] %>

但似乎rails 4无法共享引擎之间的路由问题。我在stackoverflow上发现了很多问题,但仍然无法找到一个好的解决方案。

也许这在轨道引擎中无法实现;有没有办法解决这个问题。

感谢。

2 个答案:

答案 0 :(得分:1)

我认为不可能这样做,因为每个引擎都是自己的容器,你无法跨越引擎之间来做你正在尝试做的事情。

相反,定义一个模块,您可以在两个定义相同问题的上下文中包含该模块:

module CommentableConcern
  def self.included(base)
    base.instance_eval do
      concern :commentable do
        resources :comments
      end
    end
  end
end

我认为这是你实现这一目标的唯一方法。

答案 1 :(得分:1)

在Ryan的回答(如何正确地将其包含在哪里?)中苦苦思索,我提出了以下解决方案,但未明确使用concerns但仍然共享路线:

# 1. Define a new method for your concern in a module,
# maybe in `lib/commentable_concern.rb`

module CommentableConcern
  def commentable_concern
    resources :comments
  end
end

# 2. Include the module it into ActionDispatch::Routing::Mapper to make
# the methods available everywhere, maybe in an initializer

ActionDispatch::Routing::Mapper.include CommentableConcern

# 3. Call the new method where you want
# (this way `concerns: []` does not work) obviously

Finance::Engine.routes.draw do
  resources :invoices do
    commentable_concern
  end
end

这只猴子补丁ActionDispatch::Routing::Mapper,但只要您只定义新方法(并且不触及现有方法),它应该是安全的。