【发布时间】:2016-07-22 17:00:19
【问题描述】:
我正在使用carrierwave将照片上传到我的应用程序中,照片与每个位置具有“belongs_to”关系,而位置与照片具有“has_many”关系。我是我的展示页面,其中上传了位置的照片,它们通过循环正常显示。但是,在我的索引页面中,我正在遍历我的位置并希望显示该位置的照片。照片具有正确的 location_id,我只是不确定视图中访问该位置照片的语法。我想做的是显示与特定位置相关的一张照片,例如:@photo(location.id.last)。任何帮助将不胜感激,在此先感谢。
查看
<div class="row">
<!-- featured listings gallery -->
<% @locations.each do |location| %>
<% if location.featured == "true" %>
<div class="col-md-4 col-xs-6">
<div class="thumbnail">
<div class="overlay">
<%= image_tag @photos, :size => '400x300', :class => 'img-responsive' %>
<div class="effect">
<div class="overlay-header">
<%= location.name %>
</div>
<div class="location-link">
<%= link_to "View Building", location_path(location) %>
</div>
</div>
</div>
<h3 class="display-box-caption">
<%= truncate(location.description, length: 100) %><%= link_to 'More', location_path(location), :class => 'more-info' %>
</h3>
</div>
<div class="col-md-12 property-link-container">
<%= link_to "View Building", location_path(location), :class=>"property-link" %>
</div>
</div>
<% end %>
<% end %>
</div>
控制器
class PagesController < ApplicationController
def index
@locations = Location.all
@photos = Photo.all
end
def about
end
def faqs
end
def blog
end
def whats_included
end
结束
【问题讨论】:
-
您可以像这样访问每个位置的一张照片:
<%= location.photos.last.id %>(这将为您提供最后一张照片的 id),如果只是这样做<%= location.photos.last %>(它将为您提供照片对象本身),因为您已经定义了关联。
标签: ruby-on-rails ruby