我想根据关联对象是否存在来调整我的 View 。目前我的观点是这样的
<% @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
block ,但是当没有 gallery_images 分配给锦标赛时,我没有得到“Images to follow”文本
<% @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 %>
我显然以错误的方式看待这个问题,请大家指教
谢谢
最佳答案
试试 .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>
关于ruby-on-rails - 声明关联对象是否存在 - Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23611022/