2008-11-18 32 views
3

如果我有...Rails的:檢查的has_many在查看

class Bunny < ActiveRecord::Base 
    has_many :carrots 
end 

...我怎麼能檢查在視圖如果@bunny有任何胡蘿蔔?我想要做這樣的事情:

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

我知道@bunny.carrots?不行 - 會是什麼?

回答

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

是的!謝謝!我喜歡RoR,但有時它的簡單性使其很難學習......這不是一個矛盾的術語嗎? – neezer 2008-11-18 00:19:52

1

之一:

if @bunny.carrots.length>0 

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

if @bunny.carrots.any? 

順便說一下,如果你使用IRB或腳本/控制檯需要你會發現集合的詳細操作'irb/completion'

0

@bunny.carrots是一個數組,所以你可以把它看作unless @bunny.carrots.empty?