声明是否存在关联对象 - Ruby

时间:2014-05-12 13:57:21

标签: ruby-on-rails ruby if-statement

我想根据是否存在关联对象来调整我的视图。目前我的观点是这样的

<% @tournaments.each do |t| %>
  <h3 class="gallery-header">
    <%= t.name %>
    <span class="toggle"></span>
  </h3>
  <div class="gallery-row section-body">
    <ul class="team-gallery">
      <% t.gallery_images.paginate(:page => params[:page], :per_page => 6).each do |g| %>
        <li>
          <%= link_to image_tag(g.photo.url(:gallery_small)), g.photo.url(:original), class: 'clb-photo' %>   
        </li>
      <% end %>
    </ul>
      <a href="galleries.html" class="button button-widget">View All</a>
   </div>
<% end %>

模型关联是

class Tournament < ActiveRecord::Base
  has_one :gallery, dependent: :destroy
  has_many :gallery_images, :through => :gallery, dependent: :destroy
end

class GalleryImage
  belongs_to :gallery
end

所以我虽然可以使用if块,但是当没有分配给锦标赛的gallery_images时,我没有得到“要关注的图像”文字

<% @tournaments.each do |t| %>
  <h3 class="gallery-header">
    <%= t.name %>
    <span class="toggle"></span>
  </h3>
  <div class="gallery-row section-body">
    <% if t.gallery_images %>
    <ul class="team-gallery">
      <% t.gallery_images.paginate(:page => params[:page], :per_page => 6).each do |g| %>
        <li>
          <%= link_to image_tag(g.photo.url(:gallery_small)), g.photo.url(:original), class: 'clb-photo' %>   
        </li>
      <% end %>
    </ul>
      <a href="galleries.html" class="button button-widget">View All</a>
    <% else %>
      <ul class="team-gallery">
       <li>IMAGES TO FOLLOW</li>
      </ul>
     <% end %>
   </div>
<% end %>

我显然是以错误的方式看待这个,请有人建议

由于

2 个答案:

答案 0 :(得分:5)

尝试.any?命令。

<div class="gallery-row section-body">
  <% if t.gallery_images.any? %> 
    # content
  <% else %>
    <ul class="team-gallery">
      <li>IMAGES TO FOLLOW</li>
    </ul>
  <% end %>
</div>

答案 1 :(得分:2)

t.gallery_images始终存在,但它可能是一个空数组

您可能(而不是)想要将测试编写为

<% unless t.gallery_images.empty? %>