Rails: 在视图中检查 has_many

3

If I have...

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个回答

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

是的!谢谢你!我喜欢RoR,但有时它的简单性使学习变得困难...这不是自相矛盾吗? - neezer

3
unless @bunny.carrots.empty? 

同样也可以工作


1

或者:

  if @bunny.carrots.length>0

或者

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

或者

  if @bunny.carrots.any?

顺便提一下,如果你使用irb或script/console并且需要'require'irb/completion',你将会在集合上找到更多的操作。


0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接