【问题标题】:Paperclip don't save on database回形针不保存在数据库中
【发布时间】:2018-01-18 20:20:54
【问题描述】:

我正在使用以下宝石:

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

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

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

为什么图像头像没有存储在数据库中? 我应该添加任何数据库列吗?我该怎么办?如果有任何意见可以帮助我解决这个问题,我将不胜感激。

【问题讨论】:

  • 您在尝试更新用户时是否收到任何特定的错误消息?
  • 不,我不是。没有错误信息。

标签: ruby amazon-web-services heroku amazon-s3 ruby-on-rails-5


【解决方案1】:

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

Paperclip Documentation

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

【讨论】:

  • 谢谢你,为我解答!
  • 我已经在 config/application.yml 中设置了我的 S3 存储桶,但是我没有在 User 模型上定义,因为我不知道如何在 User 模型上编写定义。我该怎么办
  • Paperclip Gem 文档是最佳选择。如果您查看 S3 特定文档,它会提供操作方法和示例:Paperclip S3 Documentation
猜你喜欢
  • 2012-10-09
  • 2013-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多