子类的不同视图 [英] Different views for subclasses

查看:38
本文介绍了子类的不同视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 STI 子类并希望针对不同的子类指向不同的视图.目前,我将子类主题路由到主类文章,如下所示:

I'm using STI subclasses and want to direct to different views for the different subclasses. At the moment I'm routing the subclass topic to the main class article like this:

 resources :topics, :controller => 'articles'

是否有一种简单的方法可以指向不同的视图?

Is there an easy way to direct to different views?

编辑

我发现的最好的方法是:

The best way I've found of doing this is:

  <% case%>
    <% when @article.type == 'Topic' %>
      <%= render 'topic' %>
    <% else %>
      <%= render 'article' %>
  <% end %>

推荐答案

如果你足够聪明地命名你的视图,你可以这样做

If you name your views smartly enough, you could just do

render @article.type

render :partial => @article.type

否则,您可以在所有 STI 子类中定义一个方法,该方法返回要显示的部分/页面的名称,这样您就可以避免控制器中的所有 if/else 逻辑.

Otherwise you could define a method in all your STI subclasses that returns the name of the partial/page to be display, that way you'll avoid all the if/else logic in your controller.

另一种方法是为不同的子类使用单独的控制器,但这不是一个好的设计.如果你要走这样一条路,那么 STI 可能毕竟不是最好的方法.

Another approach would be to have separate controllers for the different subclasses, but that is not a good design. If you were to take such a path, than maybe STI wasn't the best approach after all.

这篇关于子类的不同视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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