2012-12-02 50 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