puneeth.kumar
Wed Feb 05 2025
local_assigns :
When using partial views in Rails (like
To avoid this,
Here, the partial checks if show_projects was passed before using it. If show_projects was provided, it renders the user's projects or a message if no projects are found. If show_projects wasn't passed, nothing happens, preventing errors.
When using partial views in Rails (like
_partial.html.erb
), we might pass local variables to customize the rendering. However, if we try to use a local variable that wasn't passed, Rails will raise an error.To avoid this,
local_assigns
is a special hash that helps check if a local variable was provided when rendering the partial. Instead of directly using <%= show_projects %>
, which could cause an error if missing, we can safely check local_assigns[:show_projects]
first.
<% if local_assigns[:show_projects] %>
<%= (render @user.projects) || (render 'shared/empty_state', message: "No projects found!") %>
<% end %>
Here, the partial checks if show_projects was passed before using it. If show_projects was provided, it renders the user's projects or a message if no projects are found. If show_projects wasn't passed, nothing happens, preventing errors.