2010-08-09 31 views
1

下面是我的困境:我有兩種類型的語義上非常不同的路線,應該去不同的控制器。在Rails中處理不明確的路線

ny/new-york/brooklyn/cleaners # should go to a list of cleaners for a neighborhood 
ny/new-york/cleaners/mrclean # should go to an individual cleaner's page 

請注意,「布魯克林」和「清潔工」在這裏只是例子。該應用程序有許多服務類型(例如「更清潔」)和許多鄰居,因此不可能將任何一個列表硬編碼到正則表達式中,並使用它來區分這兩個路徑。

在路由決策中是否可以涉及訪問ActiveRecord模型的任意方法?我正在使用Rails 2.3.8。

回答

5

編輯:動態服務

望着這blog entry似乎有可能在航線使用ActiveRecords 新的答案。

也許你可以做這樣的事情:

service_names = Service.all.map(&:short_name) # assuming the property 'short_name' is the value used in urls 
service_names.each do |service_name| 
    map.connect ':state/:city/#{service_name}/:company' :controller => ‘company’, :action => ‘show’ # to show the company's page 
    map.connect ':state/:city/:neighborhood/#{service_name}_finder' :controller => ‘company_finder’, :action => ‘find’ # to list the companies for the given service in a neighborhood 
end 

這應該仍然避免由於路線的衝突一定服務是附近的路線前


老不好回答

難道你不能使用以下兩條路線嗎?

map.connect ':state/:city/cleaners/:cleaner' :controller => ‘cleaners’, :action => ‘show’ # to show the cleaner's page 
map.connect ':state/:city/:neighborhood/cleaners' :controller => ‘cleaner_finder’, :action => ‘find’ # to list the cleaners of a neighborhood 

在你的控制器,你應該能夠檢索:使用城市和其他價值PARAMS:狀態,[:狀態],則params [:城市]等

把:州/:城市/清潔工/一線清潔工應避免模棱兩可。

+1

+1。 Nitpick:無論出於何種原因,這些應該使用不同的控制器。 – alternative 2010-08-09 15:13:39

+0

修復它,謝謝。 – David 2010-08-09 15:41:20

+0

注意:「該應用程序有許多服務類型(例如'更清潔')」,因此我無法對它們全部進行硬編碼,因爲您已在此處使用「清潔工」進行硬編碼。 – lawrence 2010-08-09 16:00:32