views:

444

answers:

5

If I have...

class Bunny < ActiveRecord::Base
  has_many :carrots
end

...how can I check in the View if @bunny has any carrots? I want to do something like this:

<% if @bunny.carrots? %>
  <strong>Yay! Carrots!</strong>
  <% for carrot in @bunny.carrots %>
    You got a <%=h carrot.color %> carrot!<br />
  <% end %>
<% end %>

I know @bunny.carrots? doesn't work -- what would?

+1  A: 

either:

  if @bunny.carrots.length>0

or

unless @bunny.carrots.nil? || @bunny.carrots.length>0

or

  if @bunny.carrots.any?

by the way, you will find more operations on collections if you use irb or script/console with require 'irb/completion'

JasonTrue
+5  A: 
<% if @bunny.carrots.any? %>
  <strong>Yay! Carrots!</strong>
  <% for carrot in @bunny.carrots %>
    You got a <%=h carrot.color %> carrot!<br />
  <% end %>
<% end %>
James A. Rosen
Yes! Thank you! I love RoR but sometimes its simplicity makes it hard to learn... isn't that a contradiction in terms?
neezer
+2  A: 
unless @bunny.carrots.empty?

would work as well

madlep
A: 

@bunny.carrots is an array, so you can treat it as such by calling array methods on it, e.g. unless @bunny.carrots.empty?

Sarah Vessels
A: 

how would you expand that to find if a bunny has any orange carrots?

@bunny.carrots.any?.color == orange

i tried experimenting with a variety of options but with incorrect results.

brewster