简体   繁体   English

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

[英]declaring if an associated object is present - Ruby

I would like to adjust my view depending upon if an associated object is present. 我想根据是否存在关联的对象来调整视图。 At the moment my view looks like so 此刻我的观点看起来像是

<% @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 %>

Model associations are 模型关联是

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

class GalleryImage
  belongs_to :gallery
end

So i though i could use a if block but my when there are no gallery_images assigned to a tournament I don't get the "Images to follow" text 所以我虽然可以使用if块,但是当我没有分配给比赛的gallery_images时,我没有得到“ Images Follows”(跟随的图像)文本

<% @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 %>

Im obviously looking at this in the wrong way, could anyone advise please 我显然以错误的方式看待这个问题,有人可以建议吗

Thanks 谢谢

Try the .any? 尝试.any吗? command. 命令。

<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>

t.gallery_images is always present, but it might be an empty array t.gallery_images始终存在,但它可能是一个空数组

you might (instead) want to write the test as 您可能(而不是)想将测试编写为

<% unless t.gallery_images.empty? %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM