简体   繁体   English

如何在Rails 4应用程序中创建CMS页面路由?

[英]How to create a cms pages route in rails 4 application?

I have a CMS engine that I created and I've linked it into my main site and now I'm trying to get it to route to /about instead of /1 , which maps to the CMS Engines pages controllers show action. 我有一个创建的CMS引擎,并将其链接到我的主站点,现在我试图将其路由到/about而不是/1 ,后者映射到CMS引擎页面控制器显示操作。

example pages setup
id | name    | title      | body
1  | about   | About Us   | this is the about page
2  | contact | Contact Us | this is the contact page

It will successfully route to /1 or /2 它将成功路由到/1/2

Here is my routes.rb of the main application, which loads the cms engine 这是我的主要应用程序的routes.rb ,它加载了cms引擎

  mount Cms::Engine, :at => '/cms', :as =>'cms'
  mount Blog::Engine, :at => '/blog', :as => 'blog'

  # route to cms pages
  match ":id", :to => 'cms/pages#show', :via => [:get, :post]

Here is the show action of the CMS pages controller 这是CMS页面控制器的show动作

# GET /pages/1  or GET /pages/name
def show
  begin
     @page = Page.find_by_name(params[:id]) 
     @page ||= Page.find(params[:id]) 
  rescue
    redirect_to "/404.html"
  end
end

No matter what I try I can't get it to route the pages to /name so /about or /contact , instead I get an error that reads: Couldn't find Cms::Page with id=about or Couldn't find Cms::Page with id=contact , but if I go to /1 or /2 , then the page is rendered. 无论我尝试什么,都无法将其路由到/name以便/about/contact ,相反,我收到一条错误消息: Couldn't find Cms::Page with id=aboutCouldn't find Cms::Page with id=contact ,但是如果我转到/1/2 ,则呈现该页面。

My rake routes are: 我的耙路是:

Prefix Verb     URI Pattern    Controller#Action
 cms          /cms           Cms::Engine
blog          /blog          Blog::Engine
     GET|POST /:id(.:format) cms/pages#show

Routes for Cms::Engine:
    pages GET    /pages(.:format)          cms/pages#index
          POST   /pages(.:format)          cms/pages#create
 new_page GET    /pages/new(.:format)      cms/pages#new
edit_page GET    /pages/:id/edit(.:format) cms/pages#edit
     page GET    /pages/:id(.:format)      cms/pages#show
          PATCH  /pages/:id(.:format)      cms/pages#update
          PUT    /pages/:id(.:format)      cms/pages#update
          DELETE /pages/:id(.:format)      cms/pages#destroy
     root GET    /                         cms/login#index

Routes for Blog::Engine:
root GET / blog/index#index

OK, so I figured this out, basically show uses the id by default, so I simply created a display action and now it works. 好的,所以我弄清楚了,基本上show默认情况下使用id,所以我只创建了一个display动作,现在可以使用了。

def display
  @page = Page.find_by_name(params[:id])
  render 'public/404.html', :status => 404 if @page.nil?
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM