Rails:在View中检查has_many

时间:2008-11-18 00:08:03

标签: ruby-on-rails ruby model

如果我有......

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 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:3)

unless @bunny.carrots.empty? 

也会起作用

答案 2 :(得分:1)

或者:

  if @bunny.carrots.length>0

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

  if @bunny.carrots.any?
顺便说一句,如果你使用带有'irb / completion'的irb或script / console,你会发现有关集合的更多操作

答案 3 :(得分:0)

@bunny.carrots是一个数组,因此您可以通过调用array methods来对其进行处理,例如unless @bunny.carrots.empty?