Ruby on Rails Passing Optional Locals to Partials

Ruby on Rails Passing Optional Locals to Partials

When passing locals to Rails partials, you might run into cases where you need to pass optional locals in some places, but don’t want to pass it in every other place where you use the partial.

As an example, you have a _post partial which you render like this:

1
<%= render 'post', post: post %>

And now you want to render the same partial from another view, but this time you want to pass a boolean flag to tell the partial to render the author bio as well:

1
<%= render 'post', post: post, show_author_bio: true %>

If we used the show_author_bio local in the partial, it would break the other view which does not know this local. To use it safely, we can use the local_assigns hash:

1
2
3
4
5
6
7
<h1><%= post.title %></h1>

<% if local_assigns[:show_author_bio] %>
  <%= render 'author_bio', author: post.author %>
<% end %>

<%= post.body %>

We’re using it for passing a boolean value here, we could pass in any other object as well. For instance, we could pass in an optional author object:

1
2
3
<% if local_assigns.has_key?(:author) %>
  <%= render 'author_bio', author: author %>
<% end %>

DHH (David Heinemeier Hansson) opened an issue (#18962) about this as well, and had an interesting comment to make about this feature.

So far so good, That’s it!!! See ya!!! :)