【问题标题】:Rails: Check has_many in ViewRails:在视图中检查 has_many
【发布时间】:2008-11-18 00:08:03
【问题描述】:

如果我有...

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? 不起作用——怎么办?

【问题讨论】:

    标签: ruby-on-rails ruby model


    【解决方案1】:
    <% if @bunny.carrots.any? %>
      <strong>Yay! Carrots!</strong>
      <% for carrot in @bunny.carrots %>
        You got a <%=h carrot.color %> carrot!<br />
      <% end %>
    <% end %>
    

    【讨论】:

    • 是的!谢谢!我喜欢 RoR,但有时它的简单性让人难以学习……这不是矛盾吗?
    【解决方案2】:
    unless @bunny.carrots.empty? 
    

    也可以

    【讨论】:

      【解决方案3】:

      要么:

        if @bunny.carrots.length>0
      

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

        if @bunny.carrots.any?
      

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-05-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-14
          • 2013-02-16
          • 1970-01-01
          相关资源
          最近更新 更多