【问题标题】:Rails - How to generate routes from an Object?Rails - 如何从对象生成路线?
【发布时间】:2013-06-09 18:55:04
【问题描述】:

场景:

  • 一个主要的 Rails 应用程序
  • 各种 Rails 引擎,安装在主要 Rails 应用程序 (routes.rb) 中

现在假设我有一个名为“Engine”的引擎,里面有一个名为“Topic”的模型。 类似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'"

现在我怎样才能使它成为一个通用模式?

意味着我可以拥有任何模型的任何对象(来自各种引擎)并且我能够以干净的方式找出它的路线?

【问题讨论】:

    标签: ruby-on-rails url activerecord routes helper


    【解决方案1】:

    当您安装 rails 引擎的路线时,您可以选择传递 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)
    

    【讨论】:

    • 这不是问题所在。我可以轻松创建路线并使用它们。但问题是how to generate routes from any model Object ?
    • 很公平,对我来说听起来像是一些糟糕的架构,我用一个想法编辑了我的问题。
    • 我已经在 Rails 控制台上尝试过这个,它给出了一个错误“未定义的方法'reverse_merge!'对于 "
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    相关资源
    最近更新 更多