嘿,伙计们,我想在我家里创建一个盒子,在那里我最新的文章展示,在盒子里应该有标题和帖子的几行内容(这是相当可行的,我猜),但我也想有图像,这是在通过神社和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结束
发布于 2018-08-19 05:54:09
需要生成一个签名来处理多个文件。对于神殿,它看起来是这样的:
# 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此外,为了保持代码的一致性,您可以将其称为图像或照片。你的上传程序被称为Photos,但在其他地方它被称为Image。
您需要的最后一个更改是在控制器中接受一个图像数组,而不是一个图像。要做到这一点,您只需使用数组:
def show
@image = Image.order('RANDOM()').limit(1).first
end
private
def images_params
params.require(:images).permit(images: [)
endhttps://stackoverflow.com/questions/51912749
复制相似问题