在Rails中获取STI类基类的路由

假设我有一个带有3个模型的rails应用程序,Person,Place和Thing。 假设Thing使用单表inheritance,因此有FancyThing和ScaryThing子类。 然后是使用map.resources :people, :places, :things定义的路由map.resources :people, :places, :things 。 所以没有FancyThings和ScaryThings的控制器,ThingsController处理任何类型。

现在说我需要有代码,显示任何有链接的列表。 如果我在我的视图中有这个代码:

    

如果item是Person或Place,这可以正常工作, polymorphic_path负责生成正确的路由。 但是如果item是FancyThing或ScaryThing,这会爆炸,因为它会尝试使用没有路径的fancy_thing_path 。 我想以某种方式使它使用thing_path 。 理想情况下,Thing和/或其子类上会有一个方法以某种方式指示子类应该使用基类来生成路由。 有一个优雅的解决方案吗?

这样就可以了:

 <% @items.map {|i| if i.class < Thing then i.becomes(Thing) else i end}.each do |item| %> <%= link_to item.name, item %> <% end %> 

这使用ActiveRecord函数“变成”来对Thing基类进行Thing的所有子类的“向上转换”。

尝试使用

 map.resources :things map.resources :fancy_things, :controller => 'things' map.resources :scary_things, :controller => 'things' 

没有正确的答案,但至少我可以使用非DRY代码处理这个问题:

map.resources:things,:has_many =>:stuffs map.resources:fancy_things,:controller =>’things’,:has_many =>:stuffs map.resources:scary_things,:controller =>’things’,:has_many => :东西

希望这个问题很快就能得到纠正,因为我希望看到fancy_things只能通过:事物控制器来管理。 使用这些路线,您将结束以下url:/ fancy_things / 1,而您可能想要/ things / 1