2010-04-15 97 views
2

我有一個rails應用程序,允許使用經度和緯度進行搜索。我添加了一個 '漂亮' 的路線有:Rails漂亮的URL與小數

map.connect 'stores/near/:longitude/:latitude', :controller => 'stores', :action => 'index' 

這適用於整數緯度和經度值(http://localhost:3000/stores/near/-88/49),但未能爲十進制值(http://localhost:3000/stores/near/-88.341/49.123),並提供:

Routing Error 

No route matches "/stores/near/-88/49.0" with {:method=>:get} 

任何想法如何使用小數點在軌道中漂亮的URL?

回答

1

使用:requirements => {:param_name => pattern_regex}參數。

DECIMAL_PATTERN = /\A-?\d+(\.\d+)\z/.freeze 
map.connect 'stores/near/:longitude/:latitude', 
    :controller => 'stores', :action => 'index', 
    :requirements => { :longitude => DECIMAL_PATTERN, :latitude => DECIMAL_PATTERN } 

Parameters with dots on the URI

+0

感謝您的答覆,但它似乎並沒有工作。我仍然收到與更新之前相同的消息。當運行'rake routes'時,我得到: GET/stores/near /:longitude /:latitude {:action =>「index」,:controller =>「stores」,:requirements => {:longitude =>/A - ?\ d +(\。\ d +)\ z /,:latitude =>/\ A - ?\ d +(\。\ d +)\ z /}} – 2010-04-16 05:32:19

+1

:requirements * typo *它是:requirements – clyfe 2010-04-16 08:04:40

+1

謝謝!這有幫助!最終的解決方案需要將正則表達式修改爲:'/-?\d+(\.\d+)/'(應用程序抱怨'在路由要求中不允許錨字符')。真的很感謝解決方案和幫助! – 2010-04-16 13:21:17