首页 > 解决方案 > 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?或其他东西,但我无法将其添加到其中而不会出现错误。

标签: ruby-on-railsrubyphoto

解决方案


好的,所以我想我想通了。使用照片上的一系列条件,如果存在,我不能做一个简单的事情吗?争论。我需要创建一个 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 %>

推荐阅读