回形针不要保存在数据库中 [英] Paperclip don't save on database

查看:57
本文介绍了回形针不要保存在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下 Gems:

I am using the following Gems:

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

我想将图像保存到 S3,但无法保存.

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

迁移

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 必须配置为使用 S3 来存储对象(图像).它将在数据库中存储与这些相关联的元数据,而不是图像.

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.

请参阅 Paperclip 文档

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

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.

这篇关于回形针不要保存在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆