ruby-on-rails - Ruby on Rails 照片阵列
问题描述
我正在使用 Ruby on Rails 6.0 及更高版本的 Shrine 并试图让我的第一张照片成为我的专辑页面的封面图片。我在这里使用 Rails-Shrine-Example 工作:
https://github.com/erikdahlstrand/shrine-rails-example
我的目标是将上传照片中的第一张照片显示为封面照片,而不是相册表中的封面照片。这可能吗?
我的专辑封面代码是:
<% @albums.each do |album| %>
<tr>
<td scope="row"><%= image_tag album.cover_photo_url(:small), size: "200x200", class: "img-thumbnail" %></td>
<td scope="row"><%= album.name %></td>
<td scope="row"><%= link_to "Edit", album, class: "btn btn-default" %> <%= link_to "Show", album, class: "btn btn-default" %></td>
</tr>
<% end %>
然后在我的相册中,我能够从相册中提取第一张照片
<% @album.photo.each do |photo| %>
<div class="col-lg-3 col-md-4 col-6">
<%= image_tag photo.image.derivation_url(:thumbnail, 300, 300).to_s, :class => "img-fluid img-thumbnail" %>
</div>
<% end %>
所以我试图解释这一切,我的数据库有一个带有标题和封面照片的专辑表,还有另一个照片表。
我如何告诉它为每个相册选择该相册的照片表中的第一张图片?
*更新我能够放置这个脚本并且它在某种程度上可以工作,除了每个循环显示我的照片表中的第一张照片的次数等于上传的照片数量。我知道它是我的循环。
<% @albums.each do |album| %>
<tr>
<td scope="row">
<% album.photos.each do |photo| %>
<%= image_tag album.photos.first.image.derivation_url(:thumbnail, 300, 300), :class => "img-fluid img-thumbnail" %>
<% end %>
</td>
<td scope="row"><%= image_tag album.cover_photo_url(:small), size: "200x200", class: "img-thumbnail" %></td>
<td scope="row"><%= album.name %></td>
<td scope="row"><%= link_to "Edit", album, class: "btn btn-default" %> <%= link_to "Show", album, class: "btn btn-default" %></td>
</tr>
<% end %>
照片模型
class Photo < ActiveRecord::Base
include ImageUploader::Attachment(:image) # ImageUploader will attach and manage `image`
end
专辑型号
class Album < ApplicationRecord
has_many :photos, dependent: :destroy
accepts_nested_attributes_for :photos, allow_destroy: true
include ImageUploader::Attachment(:cover_photo) # ImageUploader will attach and manage `cover_photo`
validates_presence_of :name, :cover_photo # Normal model validations - optional
end
正如 Lurker 所分享的,我也在从没有附加照片的相册中提取信息。我不确定如何修复字符串。我知道一些 image_tags 使用 if present?或其他东西,但我无法将其添加到其中而不会出现错误。
解决方案
好的,所以我想我想通了。使用照片上的一系列条件,如果存在,我不能做一个简单的事情吗?争论。我需要创建一个 if else 语句。所以这就是我发现对我有用的东西。
<% if album.photos.present? %>
<%= image_tag album.photos.first.image.derivation_url(:thumbnail, 300, 300).to_s %>
<% else %>
<%= image_tag 'image.jpg' %>
<% end %>
推荐阅读
- python - 使用文件名作为数据框中的列标题
- android - 如果从服务更新对象,RealmObject.addChangeListener 不起作用
- python - 如何使用 Python 在 csv 行的末尾编写列表的单个元素?
- javascript - 谷歌字体 api - json 循环
- excel - 424 错误 VBA - 用户表单在我的机器上工作,但同事工作簿上出现错误
- php - 将自定义数据从联系人表单字段发布到 API 不起作用的 Mailchimp 列表
- sql - SQL Cross 适用于旋转逗号分隔值
- android - Android:仅为测试添加单独的资源
- javascript - 切换到另一个屏幕时反应导航,触发该屏幕上的功能
- asp.net-core - Swagger 中的多个 JWT