Just a quick post about a cool Rails feature you might not know about – #to_partial_path

In the app we’re currently working on, we have the concept of a Reference, which can either be given or requested. We want to render a different partial for the different types, so a first pass in our view template might look like this:

if @reference.requested?
  render "reference/requested"
elsif @reference.given?
  render "reference/given"

However, ActiveRecord models come with a #to_partial_path method baked in, so instead we can just have:

render @reference

Behind the scenes, ActionView will call #to_partial_path on our model, which we can override to contain all our logic:

def to_partial_path
  if requested?
  elsif given?

Of course, your objects don’t have to be ActiveRecord models – just something that responds to #to_partial_path.

Hope you find this useful!

Photo credit: Bairdzpics