且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

回形针不保存在数据库上

更新时间:2023-02-15 12:38:42

回形针必须配置为使用S3来存储对象(图像)。它将在数据库中存储与这些元数据相关的元数据,而不是图像。



请参阅回形针文档



您还需要为S3存储桶设置访问策略,并在用户模型中定义它们如何从S3寻址。


I am using the following Gems:

'paperclip'
'aws-sdk', '~> 2.3'

I would like to save images to S3, but am unable to get them to save.

model/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

migration

class AddAvatarToUsers < ActiveRecord::Migration[5.1]
  def self.up
    add_attachment :users, :avatar
  end

  def self.down
    remove_attachment :users, :avatar
  end
end

controllers/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

Why is the image avatar not being stored in the database? Should I add any database columns? What should I do? I would appreciate any input to help me solve this problem.

Paperclip must be configured to use S3 to store the objects (images). It will store metadata associated with these in the database, but not the images.

See Paperclip Documentation

You will also need to set an access policy for your S3 bucket, and define on the User model how they are to be addressed from S3.