我使用以下宝石:
'paperclip'
'aws-sdk', '~> 2.3'
我想将图像保存到S3,但无法让它们保存。
模型/ user.rb
class User < ApplicationRecord
# This method associates the attribute ":avatar" with a file attachment
has_attached_file :avatar, styles: {
thumb: '100x100>',
square: '200x200#',
medium: '300x300>'
}
# Validate the attached image is image/jpg, image/png, etc
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
end
迁移
class AddAvatarToUsers < ActiveRecord::Migration[5.1]
def self.up
add_attachment :users, :avatar
end
def self.down
remove_attachment :users, :avatar
end
end
控制器/ users_controller.rb
class UsersController < ApplicationController
def edit
@user = User.find_by(id: params[:id])
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
flash[:notice] = "Edit successfully"
redirect_to("/users/#{@user.id}")
end
end
private
def user_params
params.require(:user).permit(:avatar, :name, :email, :phone_number, :description, :college_name)
end
end
为什么图像头像没有存储在数据库中? 我应该添加任何数据库列吗?我该怎么办?我很感激任何帮助我解决这个问题的意见。
答案 0 :(得分:0)
必须将Paperclip配置为使用S3来存储对象(图像)。它会将与这些元数据相关的元数据存储在数据库中,但不存储图像。
您还需要为S3存储桶设置访问策略,并在用户模型上定义如何从S3处理它们。