2013-06-13 87 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>“ –

相关问题