How to Detect an Integer in Rails 3 Routes?

試著忘記壹切 提交于 2019-12-10 18:08:22

问题


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"

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"

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

(Which is my hypothetical rails syntax, to help show what I'm looking for.)

I know I can munch this in the Controller level, but it makes more sense to me to handle it at the route level.


回答1:


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"

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"


来源:https://stackoverflow.com/questions/8904029/how-to-detect-an-integer-in-rails-3-routes

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