获取 Rails 中 STI 类的基类的路由 [英] Get route for base class of STI class in Rails

查看:30
本文介绍了获取 Rails 中 STI 类的基类的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含 3 个模型的 rails 应用程序,分别是人、地点和事物.假设 Thing 使用单表继承,所以有 FancyThing 和 ScaryThing 子类.然后是用 map.resources :people, :places, :things 定义的路线.所以 FancyThings 和 ScaryThings 没有控制器,ThingsController 处理这两种类型.

Say I have a rails app with 3 models, Person, Place and Thing. Say the Thing uses single table inheritance, so there are FancyThing and ScaryThing subclasses. Then there are routes defined with map.resources :people, :places, :things. So there are no controllers for FancyThings and ScaryThings, the ThingsController handles either type.

现在说我需要有代码来显示任何有链接的东西的列表.如果我认为有此代码:

Now say I need to have code that shows a list of anything has links to them. If I have this code in my view:

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

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

If item is a Person or a Place, this works fine, polymorphic_path takes care of generating the correct route. But if item is a FancyThing or a ScaryThing, this blows up, because it will try to use fancy_thing_path, which there is no route for. I want to somehow make it use thing_path. Ideally there would be a method on Thing and/or its subclasses that somehow indicates the subclasses should use the base class to generate the route. Is there an elegant solution to this?

推荐答案

这样做可以解决问题:

<% @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 基类.

This uses the ActiveRecord function "becomes" to do an "up-cast" of all subclasses of Thing to the Thing base class.

这篇关于获取 Rails 中 STI 类的基类的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆