2012-12-02 51 views
1

我正在將我的rails應用程序移植到3.1.0(從2.3.8開始),並且正在進行重構。現在我有單獨的模型/視圖/控制器,以下兩頁。給定URL的內容覆蓋rails路徑/路徑?

http://www.youhuntandfish.com/fishing/fishingstories/148-late-fall-brook-trout http://www.youhuntandfish.com/hunting/huntingstories/104-early-nine-pointer

'huntingstories' 和 'fishingstories' 實際上是一樣的東西,所以我想分享的模型/視圖/控制器。

這是問題所在。在視圖中,我使用了像'huntingstories_path'和'fishingstories_path'這樣的助手。我不想在整個視圖中添加一堆條件來選擇要使用的條件。我想要做的是寫。

「stories_path」

而且有一些代碼,這個映射給定的「/狩獵/」或「/釣魚/」的URL的一部分打獵或是釣魚。

有沒有一種簡單的方法在路徑文件中做到這一點,還是我需要編寫視圖助手?如果我能有新的'/釣魚/故事'和'狩獵/故事'的路線,並將舊路線重新引導到這些路線,情況會更好。

這裏是現在的路線。

scope 'fishing' do 
    resources :fishingstories 
    resources :fishingspots 
end 
scope 'hunting' do 
    resources :huntingstories 
    resources :huntingspots 
end 
+0

你的路由現在看起來如何?你使用嵌套路線嗎? – nathanvda

+0

我不這樣做,但我正在使用範圍方法。我添加了上面的故事和現場路線,因爲我擁有它們。 – arons

回答

1

在聽起來自我推銷的風險,我寫了一個blog post詳細說明如何做到這一點。

如果我在你的鞋子裏,我會將fishingstorieshuntingstories改爲stories。所以,你必須像路線:

http://www.youhuntandfish.com/fishing/stories/148-late-fall-brook-trout http://www.youhuntandfish.com/hunting/stories/104-early-nine-pointer

或者只是刪除的故事完全是因爲它似乎是多餘的。無論哪種方式,代碼看起來都很相似。在您的routes.rb

[:hunting, :fishing].each do |kind| 
    resources kind.to_s.pluralize.downcase.to_sym, controller: :stories, type: kind 
end 

而在你stories_controller.rb

before_filter :find_story 

private 

def find_story 
    @story = params[:type].to_s.capitalize.constantize.find(params[:id]) if params[:id] 
end 

最後,請在您的application_controller.rb一個幫手:

helper_method :story_path, :story_url 

[:url, :path].each do |part| 
    define_method("story_#{part}".to_sym) do |story, options = {}| 
    self.send("#{story.class.to_s.downcase}_#{part}", story, options) 
    end 
end 

然後,當你輸入像story_path(@huntingstory)的Rails會自動將其轉換爲huntingstory_path(@huntingstory),同上@fishingstory ...所以你可以使用那個神奇的故事UR L任何類型的故事幫手。

+0

優秀。太糟糕了,沒有軌道/清潔的方式來做到這一點,但那會奏效。謝謝! – arons