我正在使用Rails 2.3.11。如果我有一个像http://www.abc.com/users/e.f.json这样的URL,我希望ID为'e.f',预期格式为'json'。有人可以建议一种方法吗?
谢谢!
最佳答案
由于:format约定,Rails将解析所有参数而没有任何点。如果需要,可以使用route parameters with dots:
# You can change the regex to more restrictive patterns
map.connect 'users/:id', :controller => 'users', :action => 'show', :id => /.*/
但是由于'*'和'+'正则表达式通配符都是贪婪的,因此它将完全忽略(。:format)参数。
现在,如果您绝对需要在用户名中包含点,那么有一种伪替代方法可以帮助您:
map.connect 'users/:id:format', :controller => 'users', :action => 'show', :requirements => { :format => /\.[^.]+/, :id => /.*/ }
map.connect 'users/:id', :controller => 'users', :action => 'show'
不利之处在于您必须在:format regex中包含点,否则用户名表达式将捕获该点。然后,您必须在 Controller 中处理点分格式(例如:.json)。
关于ruby-on-rails - 在Rails路线ID中有一个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6908001/