1

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.

Mischa
  • 42,876
  • 8
  • 99
  • 111
nktokyo
  • 630
  • 1
  • 7
  • 26
  • 1
    Have you tried, <% unless @fpimgblocks.blank? %> This http://stackoverflow.com/questions/885414/a-concise-explanation-of-nil-v-empty-v-blank-in-ruby-on-rails might help – Anand Shah Oct 21 '10 at 14:08

1 Answers1

6

@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
  • 23,051
  • 7
  • 53
  • 50
  • 2
    .blank? is probably better in this case, as it handles the case @fpimgblocks is nil. Otherwise @fpimgblocks.empty? will cause a NoMethodError. – Jason Noble Oct 21 '10 at 15:49
  • 2
    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 Oct 21 '10 at 15:52