我正在使用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
端
答案 0 :(得分:2)
在协会的帮助下访问照片:
location.photos.last.photo.url
HTML
<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">
<!-- changing @photos to location.photos.last -->
<% if location.photos.any? and location.photos.photo.present? %>
<%= image_tag location.photos.last.photo.url, :size => '400x300', :class => 'img-responsive' %>
<% end %>
<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>
控制器:
def index
@locations = Location.all
# no need to fetch photos now
# @photos = Photo.all
end
照片模特
class Photo < ActiveRecord::Base
belongs_to :location
mount_uploader :photo, PhotoUploader
end
答案 1 :(得分:1)
我看到Sahil的帖子得到了帮助。添加.includes(:photos)
,以更快地加载查询。在未来,将是非常有用的。
def index
@locations = Location.includes(:photos).all
end