【发布时间】:2016-10-29 22:03:18
【问题描述】:
相册有很多图片。为了在索引页面上显示我的所有专辑,我想要一张专辑第一张图片的缩略图。与其在相册中添加附件,我想知道是否有一种方法可以从该特定相册中提取第一张图片。
这是我目前拥有的:
专辑/index.html.erb
<% @albums.each do |a| %>
<div class="thumbnail">
<%= link_to image_tag(a.images.first(:thumb)), a %>
<div class="caption">
<h3><%= a.title %></h3>
<p><%= a.description %></p>
</div>
</div>
<% end %>
models/image.rb
class Image < ActiveRecord::Base
belongs_to :album
has_attached_file :photo,
styles: { large: "700x700>", medium: "450>", thumb: "200x200>" },
storage: :s3,
s3_credentials: Proc.new{ |a| a.instance.s3_credentials }
validates_attachment_content_type :photo, content_type: /\Aimage\/.*\Z/
validates_presence_of :title
validates_presence_of :album_id
def s3_credentials
{
access_key_id: ENV["AWS_ACCESS_KEY_ID"],
secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"],
s3_region: ENV["AWS_REGION"],
bucket: ENV["S3_BUCKET_NAME"]
}
end
end
我收到一个错误“无法将符号转换为整数”,它指向带有 image_tag 的行
【问题讨论】:
-
检查 a.images 是否真的是一个数组或散列!
-
试试
a.images[0].first(:thumb) -
@mahatmanich 然后我在尝试
<%= link_to image_tag(a.images[0].first(:thumb)), a %>时收到“undefined method 'first' for #<0x007fca9a4601d8>0x007fca9a4601d8>