3

如果我有...

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?这行不通——怎么办?

4

4 回答 4

8
<% if @bunny.carrots.any? %>
  <strong>Yay! Carrots!</strong>
  <% for carrot in @bunny.carrots %>
    You got a <%=h carrot.color %> carrot!<br />
  <% end %>
<% end %>
于 2008-11-18T00:16:30.647 回答
3
unless @bunny.carrots.empty? 

也可以

于 2008-11-18T00:26:58.753 回答
1

任何一个:

  if @bunny.carrots.length>0

或者

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

或者

  if @bunny.carrots.any?

顺便说一句,如果你使用 irb 或 script/console with require 'irb/completion' 你会发现更多关于集合的操作

于 2008-11-18T00:14:32.133 回答
0

@bunny.carrots是一个数组,因此您可以通过在其上调用数组方法来处理它,例如unless @bunny.carrots.empty?

于 2008-11-20T23:44:44.017 回答