Rails从文章中调用图像,该图像通过神社上传到文章中

时间:2018-08-18 21:37:32

标签: ruby-on-rails ruby image shrine

伙计们,我想在我家中创建一个框,其中显示了我最近的文章,在框中应该有帖子的标题和几行内容(我想这是相当可行的),但我也希望通过shrine和trix上传帖子中的图片。 一般来说,我不知道如何从帖子中获取图像以使用它们。我知道如果会有更多图像可能会很困难,但是我想将它们随机化。

我的模型post.rb

class Post < ApplicationRecord
  validates :title, :content, :presence => true
  extend FriendlyId
  friendly_id :title, use: :slugged
end

我的模型image.rb

class Image < ApplicationRecord
# adds an `image` virtual attribute
include ::PhotoUploader::Attachment.new(:image)

end

我的图像控制器

class ImagesController < ApplicationController
  respond_to :json

  def create
    image_params[:image].open if image_params[:image].tempfile.closed?

    @image = Image.new(image_params)

    respond_to do |format|
      if @image.save
        format.json { render json: { url: @image.image_url }, status: :ok }
      else
        format.json { render json: @image.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  def image_params
    params.require(:image).permit(:image)
  end

结束

1 个答案:

答案 0 :(得分:0)

您需要生成一个签名来处理多个文件。有了神社,它看起来像这样:

# db/migrations/001_create_photos.rb
create_table :images do |t|
  t.integer :imageable_id
  t.string  :imageable_type
  t.text    :image_data
  t.text    :image_signature
end
add_index :images, :image_signature, unique: true

# app/uploaders/image_uploader.rb
class ImageUploader < Shrine
  plugin :signature
  plugin :add_metadata
  plugin :metadata_attributes :md5 => :signature

  add_metadata(:md5) { |io| calculate_signature(io) }
end

# app/models/image.rb
class Image < ApplicationRecord
  include ImageUploader::Attachment.new(:image)
  belongs_to :imageable, polymorphic: true

  validates_uniqueness_of :image_signature
end

出于一致性考虑,在代码中也可以将其称为图片或图片。您的上传者称为“照片”,但其他所有地方均称为“图像”。

您需要做的最后一个更改是在控制器中,使其接受一列图像而不是一个图像。为此,您只需使用数组即可:

def show
  @image = Image.order('RANDOM()').limit(1).first
end

private
def images_params
  params.require(:images).permit(images: [)
end