2013-06-13 18 views
1

場景:Rails - 如何從一個對象生成路由?

  • 一個主要的Rails應用程序
  • Rails的各種發動機,安裝在主Rails應用程序(的routes.rb)

現在假設我有一個引擎命名爲 「引擎」 裏邊有是名爲「主題」的模型。 喜歡的東西Engine::Topic < ActiveRecord::Base

現在這種發動機內,如果我要生成的Topic任何實例條路,我會做這樣的事情:

@topic = Engine::Topic.first 

# inside helpers/views, i can write the below statement 

url_for ([@topic]) 

# and it will give me exact "show" route for this topic. Like "/engine/topic/1" 
# But this works only inside engines. If i write this inside main Application, 
# it gives an error "undefined method 'topic_path'" 

現在我怎樣才能讓這個廣義的模式?

意味着我可以有任何模式的任何對象(從各種發動機)和我將能夠找出其路徑在一個乾淨的方式?

回答

0

當你安裝一個導軌引擎的路線,你可以選擇通過as

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

這將爲您提供路線助手my_engine,這樣就可以使用my_engine.root_url例如,訪問您的發動機路線。

來源:http://edgeapi.rubyonrails.org/classes/Rails/Engine.html

編輯:

也許你可以做一些事情元這樣的嗎? :/

@topic.class.parent::Engine.routes.url_for(@topic) 
+0

這不是問題。我可以輕鬆創建我的路線並使用它們。但問題是'如何從任何模型對象路線?' –

+0

很公平,聽起來似乎有些可憐的架構給我,我編輯的一個想法,我的問題。 –

+0

我已經嘗試過這個軌控制檯上,它提供了一個錯誤「未定義的方法‘reverse_merge!’ for <#Engine :: Topic 34d34es4e>「 –

相關問題