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

时间:2009-03-31 19:44:26

标签: ruby-on-rails ruby

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

现在说我需要有代码,显示任何包含链接的列表。如果我在我看来有这个代码:

<% @items.each do |item| %>
  <%= link_to item.name, item %>
<% end %>

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

3 个答案:

答案 0 :(得分:12)

这样可以解决问题:

<% @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的所有子类进行“向上转换”。

答案 1 :(得分:8)

尝试使用

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

答案 2 :(得分:0)

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

map.resources:things,:has_many =&gt; :东西 map.resources:fancy_things,:controller =&gt; 'things',:has_many =&gt; :东西 map.resources:scary_things,:controller =&gt; 'things',:has_many =&gt; :东西

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