Rails部分具有单表继承

时间:2011-05-03 07:06:47

标签: ruby-on-rails

我想在rails中使用partials以及单表继承。我目前有这个工作:

render partial: @vehicle

# which renders the relevant view, depending on object type, eg:
#   views/trucks/_truck.haml
#   views/car/_car.haml

我想保留这些默认视图,并为每个对象创建一个额外的紧凑视图,也许就像这样

# example code only, I want to write something like:
render partial: 'compact', locals: {vehicle: @vehicle}

# and then have this render (for example) with
#   views/trucks/_compact.haml
#   views/car/_compact.haml

我可以愉快地重命名或更改文件名或位置,但支持两种视图(紧凑和默认)的最简单方法是什么?

稍后会有更多的课程,所以寻找非常干净,优雅的代码。

(ruby 1.9.2上的rails 3.0.5+)

3 个答案:

答案 0 :(得分:13)

要准确了解您的要求,请执行以下操作:

render partial: "#{@vehicle.type.tableize}/#{@vehicle.type.underscore}", object: @vehicle

你会得到渲染:

views/trucks/_truck.html.haml

,对象将可以访问:

@truck

答案 1 :(得分:3)

可能有更好的方法,但始终有这种方法:

render partial: "#{@vehicle.class.to_s.tableize}/compact", locals:{vehicle: @vehicle}

(或者它可能需要_compact,而不仅仅是紧凑,但你明白了)

答案 2 :(得分:1)

我做了类似的事情,但是我把它们组合在一起,而不是将它们放在两个单独的文件中,并使用locals参数传递一个标志:

# The hash syntax for render is redundant, you can simply pass your instance
# Render the long-form of your partial
render @vehicle

# When using render _instance_, the second argument becomes the locals declaration
# Render the compact form
render @vehicle, compact: true

然后,在我的部分......

<% if defined? compact %>
  <!-- HTML for compact view -->
<% else %>
  <!-- HTML for extended view -->
<% end %>

这种方法的优点是,您只为每种车型维护一个部分文件,并且您的代码保持原始状态。

缺点是它与偏见的“传统”使用略有不同。

相关问题