如何在Rails 3路由中检测整数? [英] How to Detect an Integer in Rails 3 Routes?
问题描述
我只想在rotues.rb中做一点额外的逻辑,这也许不属于那里,但是对我来说似乎最有意义。
I would like to do just a little bit of extra logic in rotues.rb, that probably doesn't belong there, but it seems to make the most sense to me.
我有两条相互冲突的路线。简而言之:
I have two conflicting routes. To be primitive:
match '/videos/:browseby' => 'videos#browse', :as => "browse_by"
其中:browseby正在查找字符串,例如标签,以浏览视频
Where :browseby is looking for a string, such as "Tags", to browse videos by tags.
但是,(而且很有可能看到了这种情况)我也有基本的表演资源(同样以原始形式):
However, (and most probably saw this coming) I also have my basic show resource (again in primitive form):
match '/videos/:id' => 'videos#show', :as => "video"
其中:id正在寻找视频ID的整数。
Where :id is looking for the integer for the video ID.
有没有办法添加一点逻辑,例如...
Is there a way to add a small bit of logic such as...
match '/videos/:id' => 'videos#show', :as => "video", :format(:id) => :integer
(这是我假设的rails语法,以帮助显示我在寻找什么。)
(Which is my hypothetical rails syntax, to help show what I'm looking for.)
我知道我可以在Controller级别进行修改,但是在路由级别处理它对我来说更有意义。
I know I can munch this in the Controller level, but it makes more sense to me to handle it at the route level.
推荐答案
您可以尝试使用:constraints
和正则表达式:
You could try using :constraints
and a regex:
match '/videos/:id' => 'videos#show', :as => "video", :constraints => { :id => /\d/ }
match '/videos/:browseby' => 'videos#browse', :as => "browse_by"
您还需要确保宽松的:browseby
版本在:id
版本之后。请注意,正则表达式约束是在开始时隐式锚定的,因此只要您的:browseby
值不是以数字开头。
You'll also want to make sure the looser :browseby
version comes after the :id
version. Note that regex constraints are implicitly anchored at the beginning so that would work as long as your :browseby
values didn't start with a number.
如果您有以数字开头的标签,则您可以使用对象作为约束,然后可以在正则表达式中包含锚:
If you have tags that do start with numbers then you could use an object for the constraint and then you could include anchors in your regex:
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"
这篇关于如何在Rails 3路由中检测整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!