23

我有一個Rails 3應用程序與幾個引擎包含附加功能。每個引擎都是一項獨立的服務,客戶可以購買訪問權限。如何從主機應用程序提供Rails 3引擎的路由?

但是,我有一個問題,來自引擎的路由,這些引擎對於控制器和視圖來說並不容易獲得。

控制器:

class ClassroomsController < ApplicationController 
    .. 
    respond_to :html 

    def index 
    respond_with(@classrooms = @company.classrooms.all) 
    end 

    def new 
    respond_with(@classroom = @company.classrooms.build) 
    end 

    .. 
end 

app/views/classrooms/new.html.haml

= form_for @classroom do |f| 
    .. 
    f.submit 

在發動機config/routes.rb

MyEngineName::Engine.routes.draw do 
    resources :classrooms 
end 

config/routes.rb在應用程式:

Seabed::Application.routes.draw do 
    mount MyEngineName::Engine => '/engine' 
    ... 
end 

發動機lib/my_engine_name.rb

module MyEngineName 
    class Engine < ::Rails::Engine 
    end 
end 

試圖去/classrooms/new結果

NoMethodError in Classrooms#new 

Showing app/views/classrooms/_form.html.haml where line #1 raised: 
    undefined method `hash_for_classrooms_path' for #<Module:0x00000104cff0f8> 

,並試圖調用classrooms_path從同樣的錯誤任何其他查看結果。 但是,我可以撥打MyEngineName::Engine.routes.url_helpers.classrooms_path並使其正常工作。我想我可能已經定義了錯誤的路線,但找不到另一種方法。

嘗試使用Passenger(獨立和Apache模塊)和WEBrick(rails服務器)運行應用程序。使用Git的最新Rails(7c920631ec3b314cfaa3a60d265de40cba3e8135)。

回答

25

變化config.routes在您的發動機:

Rails.application.routes.draw do # NOT MyEngineName::Engine.routes.draw 
    resources :classrooms 
end 

你有它的方式,路由僅在MyEngineName::Engine命名空間中可用,而不是在主機Rails應用程序的其餘部分。

曾經有一個博客帖子有更多的信息,但遺憾的是它不再可用:

+0

做的是,除在我的應用程序的路由安裝呼叫和範圍界定在發動機路線(`scope'/ engine'do`),一切正常。非常感謝:) – PerfectlyNormal 2010-12-06 00:57:06

+0

很酷,感謝獲取引擎路線工作所需的其他步驟信息。 – bowsersenior 2010-12-06 03:27:24

26

我有同樣的問題,並發現了這個在documentation

既然你現在可以安裝內部應用程序的路由引擎,你不必引擎的直接訪問應用程序中的url_helpers。當您在應用程序的路線中安裝引擎時,會創建一個特殊幫助程序以允許您執行此操作。考慮這樣一個場景:

# config/routes.rb 
MyApplication::Application.routes.draw do 
    mount MyEngine::Engine => "/my_engine", :as => "my_engine" 
    get "/foo" => "foo#index" 
end 

現在,您可以使用my_engine幫助你的應用程序中:

class FooController < ApplicationController 
    def index 
    my_engine.root_url #=> /my_engine/ 
    end 
end