动态 CMS 类似于 ruby​​ on rails 中的路由 [英] Dynamic CMS like routes in ruby on rails

查看:42
本文介绍了动态 CMS 类似于 ruby​​ on rails 中的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类似 CMS 的网站,用户从一些通用页面开始,即

I want to create a CMS like site where the user starts off with a some generic pages, i.e.

  • 主页
  • 关于
  • 联系方式

从那里可以动态添加子页面,例如

and from there can add child pages dynamically, for example

  • 主页
    • 文章
      • 文章1
        • 某事
          • 别的东西

          为了实现这一点,我计划使用某种自我引用关联,例如

          To achieve this I'm planning on using some kind of self-referential association like

          class Page < ActiveRecord::Base
            belongs_to :parent, :class_name => 'Page'
            has_many :children, :class_name => 'Page'
          end
          

          我正在努力解决的一件事是路线生成.因为可以动态添加页面,所以我需要为这些页面动态生成路由,并且无法知道页面可以嵌套多少层

          The one thing I'm struggling with is the route generation. Because pages can be added on the fly I need to dynamically generate routes for these pages and there is no way of knowing how many levels deep a page may be nested

          所以如果我从主页开始:/

          So if I start off with the homepage: /

          然后开始添加页面,即

          /articles/article1/something/something-else/another-thing

          /articles/article1/something/something-else/another-thing

          如何使用 rails 路由模型实现类似的功能?

          How can something like that be achieved with the rails routing model?

          推荐答案

          一旦你有办法为你的 Page 记录生成 URL 字符串(我会把这部分留给你),你可以只映射 config/routes.rb 中的每个页面:

          Once you have some way to generate the URL string for your Page records (and I'll leave that part up to you), you can just map every page in config/routes.rb:

          Page.all.each do |page|
            map.connect page.url, :controller => 'pages', :action => 'show', :id => page
          end
          

          并让观察者钩住页面模型以在发生变化时重新加载路由:

          And have an observer hook the page model to reload routes when something changes:

          class PageObserver < ActiveRecord::Observer
            def reload_routes(page)
              ActionController::Routing::Routes.reload!
            end
            alias_method :after_save,    :reload_routes
            alias_method :after_destroy, :reload_routes
          end
          

          不要忘记编辑 config/environment.rb 以加载观察者:

          Don't forget to edit config/environment.rb to load the observer:

          # Activate observers that should always be running
          config.active_record.observers = :page_observer
          

          这篇关于动态 CMS 类似于 ruby​​ on rails 中的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆