【问题标题】:Sharing routing concerns between rails engines在 Rails 引擎之间共享路由问题
【发布时间】:2014-02-11 22:26:20
【问题描述】:

我有两个不同的隔离可安装导轨引擎;一个命名为 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 文件,如下所示; 宝石文件;

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

routes.rb;

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

在金融宝石; invoice show.erb 有如下评论表单;

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

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

也许这在 Rails 引擎中不可用;有没有办法两个处理这个。

谢谢。

【问题讨论】:

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


    【解决方案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,但只要你只定义新方法(并且不触及现有方法)它应该是安全的。

    【讨论】:

    • 这应该是公认的答案,Ryan 的答案似乎不起作用,正如其他人也发现的那样,Markus 的答案确实有效。
    【解决方案2】:

    我认为这是不可能的,因为每个引擎都是它自己的容器,您无法跨越引擎来执行您正在尝试执行的操作。

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

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

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

    【讨论】:

    • 谢谢瑞恩,你救了我的命。
    • 我已经为此苦苦挣扎了几个小时。我如何在两个不同的路由集中实际包含这个问题?
    • 我也遇到这个问题。既然comments是在一个引擎中定义的,那么其他引擎是如何解决的呢?
    • 我无法让include 在我的路线内工作。对我有用的是直接在路由中调用 included(base) 方法,如 CommentableConcern.included(self) 。为了减少混淆,我将方法名称从included 更改为apply,但其他实现完全相同。
    猜你喜欢
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多