Ruby on Rails Photo Array
我正在Shrine中使用Ruby on Rails 6.0及更高版本,并试图将我的图像的第一张照片用作"相册"页面的封面图像。我正在从Rails-Shrine-Example这里进行工作:
https://github.com/erikdahlstrand/shrine-rails-example
我的目标是将上传的照片中的第一张照片显示为封面照片,而不是相册表中的cover_photo。这可能吗?
我的专辑封面代码是:
1 2 3 4 5 6 7 | <% @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 %> |
然后在我的相册中,我可以使用
从相册中提取第一张照片
1 2 3 4 5 | <% @album.photo.each do |photo| %> <%= image_tag photo.image.derivation_url(:thumbnail, 300, 300).to_s, :class =>"img-fluid img-thumbnail" %> <% end %> |
为了让我尽力解释这一切,我的数据库有一个带标题和封面照片的相册表,还有一张用于存放照片的表。
如何告诉它为每个专辑选择该专辑的照片表中的第一张图像?
*更新
我能够放置此脚本,并且它在某种程度上可以工作,除了每个循环在我的照片表中显示第一张照片的次数等于上载的照片数量。我知道它是我的循环。
1 2 3 4 5 6 7 8 9 10 11 12 | <% @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 %> |
照片模特
1 2 3 | class Photo < ActiveRecord::Base include ImageUploader::Attachment(:image) # ImageUploader will attach and manage `image` end |
专辑模型
1 2 3 4 5 6 7 8 | 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表示吗?之类的东西,但是我不能无误地将其添加到其中。
好,所以我想我明白了。有了照片上的条件条件,如果存在的话,我不能做简单的事情吗?争论。我需要创建一个if else语句。所以这是我发现对我有用的。
1 2 3 4 5 | <% if album.photos.present? %> <%= image_tag album.photos.first.image.derivation_url(:thumbnail, 300, 300).to_s %> <% else %> <%= image_tag 'image.jpg' %> <% end %> |