Rails partials with single-table inheritance
I want to use partials in rails along with single-table inheritance. I currently have this working:
render partial: @vehicle
# which renders the relevant view, depending on object type, eg:
# views/trucks/_truck.haml
# views/car/_car.haml
I want to leave these default views in place, and create an addi开发者_JAVA技巧tional compact view for each object, perhaps like this
# 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
I can happily rename things or change the file names or locations, but what is the simplest way to support two kinds of views (compact and default)?
There will be many more classes later, so looking for very clean, elegant code.
(rails 3.0.5+ on ruby 1.9.2)
To get exactly what you asked for you should do this:
render partial: "#{@vehicle.type.tableize}/#{@vehicle.type.underscore}", object: @vehicle
and you will get rendered:
views/trucks/_truck.html.haml
and the object will be accessible as:
@truck
There might be a better way, but there is always this approach:
render partial: "#{@vehicle.class.to_s.tableize}/compact", locals:{vehicle: @vehicle}
(or it might need to be _compact, instead of just compact, but you get the idea)
I've done something similar, but rather than having the partials in two separate files, I've combined them, and used the locals
argument to pass a flag:
# 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
And then, in my partial...
<% if defined? compact %>
<!-- HTML for compact view -->
<% else %>
<!-- HTML for extended view -->
<% end %>
The advantages of this approach are that you're only maintaining one partial file for each vehicle type, and your code remains pristine.
The disadvantage is that it's a slight departure from the "traditional" usage of partials.
精彩评论