简体   繁体   English

Rails 路由:如何让控制器串联以响应相同的匹配路径

[英]Rails Routing: How to have controllers in series to respond to same matching path

In my Rails routes.rb file I'm wanting to do something like the following.在我的 Rails routes.rb 文件中,我想做如下事情。

  get '/:id' => 'pages#show'
  get '/:id' => 'articles#show'

So that if a visitor types in这样,如果访客输入

http://www.example.com/about-this-site

The pages controller in the above example would get first shot at handling it.上面示例中的 pages 控制器将首先处理它。 Then if not, the next controller in line would get a shot.如果没有,那么排队的下一个控制器将获得一次机会。

REASONs for wanting to do this:想要这样做的原因:

1) I'm trying to port my Wordpress site over without establishing new urls for all my pages and blog posts. 1) 我正在尝试移植我的 Wordpress 网站,而没有为我的所有页面和博客文章建立新的 url。 As it stands, all of my blog post files and pages are accessed directly off the root uri '/' folder.就目前而言,我所有的博客文章文件和页面都直接从根 uri '/' 文件夹中访问。

2) Because I'm not able to, it's a learning thing for me. 2)因为我做不到,这对我来说是一件学习的事情。 But, I want to do it without a hack.但是,我想在没有黑客的情况下做到这一点。

How about redirecting to the second controller from your first controller?从第一个控制器重定向到第二个控制器怎么样?

in PagesController在页面控制器中

def show
  unless Page.find_by(id: params[:id])
    redirect_to controller: :articles, action: :show, id: params[:id]
  end
end

in ArticlesController在文章控制器中

  def show
    # Handle whatever logic here...
  end

Edit编辑

If you really don't want to redirect then you can consolidate the logic into a single action:如果您真的不想重定向,则可以将逻辑合并为一个操作:

def show
  if Page.find_by(id: params[:id])
    render :show
  elsif Article.find_by(id: params[:id])
    render controller: :articles, action: :show
  else
    # Handle missing case, perhaps a 404?
  end
end

However, I'd recommend using a redirect if possible.但是,如果可能,我建议使用重定向。 It's a cleaner solution and keeps your controller code isolated.这是一个更干净的解决方案,并保持您的控制器代码隔离。

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

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