Rails wildcard route with database lookup & multiple controllers

此生再无相见时 提交于 2019-12-11 10:24:47

问题


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.

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.

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

In other words, where might this logic properly go?

Thanks.


回答1:


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


来源:https://stackoverflow.com/questions/24816830/rails-wildcard-route-with-database-lookup-multiple-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!