views:

30

answers:

1

Hello, 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.

+6  A: 

@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!

Jaime Bellmyer
.blank? is probably better in this case, as it handles the case @fpimgblocks is nil. Otherwise @fpimgblocks.empty? will cause a NoMethodError.
Jason Noble
You're right, it would - although I like `empty?` because it's more specific, and there's never a case where you would get a nil when you're calling `Object.all` or `Object.find(:all)`, which is the case in this example.
Jaime Bellmyer
perfect, thanks!
nktokyo