Paperclip don't save on database

2019-09-15 22:52发布

问题:

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.

回答1:

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.