How To Use Optional Local Variables In A Partial In Rails

Posted by Weston Ganger on September 06, 2016

Here are a few methods to work with optional local variables in a partial.

These examples show unless foo is defined then make foo = ‘bar’.

# Method 1, Simple & Concise but won't work well for booleans or nil
<% foo ||= 'bar' %>

# Method 2
# If the second/default value here is a method, use this syntax to prevent premature call of the method
<% foo = local_assigns.fetch(:foo){ Post.all } %>
# Else, use this syntax
<% foo = local_assigns.fetch(:foo, 'bar') %>

This example intends these to be added at the top of your partial. You can easily adapt them to be used in place if its only a one time use.

Related External Links:

Posted in Rails and Tagged with rails partial 

Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts