如何在 rails 中添加示例图片

how to add a sample image in rails

我有一个简单的 rails 网站,人们可以在其中 post 运送带有图像的货物,为此我使用 paperclip gem 但我的问题是如果用户添加没有上传图片的货件,它得到 posted 但没有图片,但我想要的是添加一个示例图片,这样如果有人添加了一个没有图片的货件,将自动生成一个示例图片

我的代码:

<div class="container-fluid">
<div id="post_show">
  <h1>
    <strong><font style="text-transform: capitalize;"><%= @shipment.name %></strong></font>
  </h1>
  <p></p>
  <p class="username">
    Added by
    <strong><font style="text-transform: capitalize;"><%= @shipment.user.full_name %></strong></font>
    about
    <%= time_ago_in_words(@shipment.created_at) %>
  </p>
  <div class="clearfix">
    <div class="post_image_description">
      <%= image_tag @shipment.image.url(:medium) %>
      <div class="description">
        <%= simple_format(@shipment.description) %>
      </div>
    </div>

form.html.erb

<div class="form-row">
  <div class="field">
    <%= f.label :image, label: "Add An Image Of The Shipment" %><br>
    <%= f.file_field :image %>
  </div>
</div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</div>

您可以使用选项 default_url

指定回形针中缺少的图像路径

型号:

has_attached_file :image, :default_url => "/images/normal/missing.png"

使用 default_url 使其始终有图像。它是回形针的一个选项

检查这个 https://github.com/thoughtbot/paperclip#user-content-models

有一个选项 default_url 以防图像未上传然后作为默认图像 /images/:style/missing.png 您还可以在此处指定您自己的特定图像路径以显示为默认图像。

这是取自回形针文档的示例 (Rails 4):

class User < ActiveRecord::Base
  has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/
end

您可以使用以下条件显示:

<%= image_tag @shipment.image.url.present? ? @shipment.image.url(:medium) : "your_default_image.png" %>