Try the .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>
Question
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
<% @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
Solution
Try the .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>
OTHER TIPS
t.gallery_images is always present, but it might be an empty array
you might (instead) want to write the test as
<% unless t.gallery_images.empty? %>