Rails通配符路由与数据库查找&多个控制器 [英] Rails wildcard route with database lookup & multiple controllers

查看:314
本文介绍了Rails通配符路由与数据库查找&多个控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails应用程序设置,其中,在定义所有其他网站路由后,我有一个全部通配符为我的用户显示他们的个人档案选定的根级别的虚荣URL非预留路径/关键字:

I have a Rails application setup where, after all of the other site routes are defined, I have a catch-all wildcard for my Users to display their Profiles on selected root-level "vanity" URLs of non-reserved paths/keywords:

get '*path' => 'profiles#show'

个人资料控制器会检查以确保路径定义有效的配置文件,否则重定向到根。这个工作正常。

The Profiles controller then checks to make sure the path defines a valid Profile, otherwise redirects to root. This works fine.

我现在需要做的是创建一个机制,其中catch-all 路径可以定义 a Profile 一个博客,根据路径的数据库查找路由到正确的控制器。

What I need to do now is create a mechanism where the catch-all path could define either a Profile or a Blog, based on the database lookup of the path for the proper controller to route to.

我不想执行重新导向...我想在原始通配符网址载入个人资料或网志内容。

I do not want to do a redirect ... I want to load either the Profile or Blog content on the original wildcard URL.

我的选项是从通配符路径 - > db查找 - >正确的控制器?

What are my options to go from wildcard route -> db lookup -> proper controller?

换句话说,这个逻辑在哪里可以正常?

In other words, where might this logic properly go?

谢谢。

推荐答案

看起来你想要一个路由约束匹配一些模式路径匹配路由,或者如果尝试后续路由。也许这样的。

It seem like you want a route constraint that will match some pattern (regex) that defines if a path matches a route or if it tries the subsequent routes. Maybe something like this.

get '*path', :to => 'profiles#show', :constraints => { path: /blog\/.+/ }

这个想法是你必须知道路由级别,如果它可以基于路径,则上述事情将工作,否则如果需要更复杂,您可以使用自定义约束类。

The idea is that you must know something at the routing level, if it can be path based then the above thing will work otherwise if it needs to be more complex you can use a custom constraints class.

# lib/blog_constraint.rb
class BlogConstraint
  def initialize
    @slugs = Blog.pluck(:slug)
  end

  def matches?(request)
    request.url =~ /blog\/(.+)/
    @slugs.include?($1)
  end
end

# config/routes.rb
YourApp::Application.routes.draw do
  get '*path', :to => 'blogs#show', :constraints => BlogConstraint.new
  get '*path', :to => 'profiles#show'
end

这篇关于Rails通配符路由与数据库查找&多个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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