ruby – render based on a condition, rails – Education Career Blog

I have a form displaying a nested relationship. The call to render the nested child objects is made like below:

<% if @fpimgblocks %>
  <% f.fields_for @fpimgblocks do |builder| %>
    <%= render 'fpimgblock_fields', :f => builder %>
  <% end %>
<% end %>

@fpimgblocks is the result of a find, I have verified there are zero results so I expect this to not render. However, the partial is rendered even through the object is not initialized. This then returns a nil_class error when I commit the form.

Is the syntax in the if statement wrong or something? I’ve tried changing to “unless @fpimgblocks.nil? but no change.

,

@fpimgblocks is not nil as you’re expecting. Since it’s the result of a find, it’s actually an empty array. Change this:

<% if @fpimgblocks %>

to this:

<% unless @fpimgblocks.empty? %>

And it will work. I hope this helps!

Leave a Comment