我想在rotues.rb中只做一个小的额外逻辑,这可能不属于那里,但它似乎对我来说最有意义。
我有两条相互矛盾的路线。要原始:
match '/videos/:browseby' => 'videos#browse', :as => "browse_by"
其中:browseby正在寻找一个字符串,例如“标签”,以按标签浏览视频。
然而,(并且很可能看到了这一点)我也有我的基本节目资源(再次以原始形式):
match '/videos/:id' => 'videos#show', :as => "video"
其中:id正在查找视频ID的整数。
有没有办法添加一些逻辑,比如......
match '/videos/:id' => 'videos#show', :as => "video", :format(:id) => :integer
(这是我假设的rails语法,以帮助显示我正在寻找的内容。)
我知道我可以在Controller级别中修复它,但在路由级别处理它更有意义。
答案 0 :(得分:5)
您可以尝试使用:constraints
和正则表达式:
match '/videos/:id' => 'videos#show', :as => "video", :constraints => { :id => /\d/ }
match '/videos/:browseby' => 'videos#browse', :as => "browse_by"
您还需要确保在:browseby
版本之后找到更宽松的:id
版本。请注意regex constraints are implicitly anchored at the beginning,只要您的:browseby
值不是以数字开头,就可以正常工作。
如果您的标签以数字开头,则可以use an object for the constraint,然后您可以在正则表达式中包含锚点:
class VideoIdsOnly
def matches?(request)
request.path =~ %r{\A/videos/\d+\z}
end
end
match '/videos/:id' => 'video#show', :as => "video", :constraints => VideoIdsOnly.new
match '/videos/:browseby' => 'videos#browse', :as => "browse_by"