我正在使用 carrierwave 将照片上传到我的应用程序中,照片与每个位置都有“belongs_to”关系,而位置与照片有“has_many”关系。我是我的展示页面,其中上传了位置照片,它们通过循环正常显示。但是,在我的索引页面中,我正在遍历我的位置并希望显示该位置的照片。照片具有正确的 location_id,我只是不确定 View 中用于访问该位置照片的语法。我想做的是显示与特定位置相关的照片之一,例如:@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>
Controller
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.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>
Controller :
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
关于ruby-on-rails - 如何访问 View 中的实例变量 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36380865/