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

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

问题描述

我使用以下宝石:

 'paperclip'
'aws-sdk','〜> ; 2.3'

我想将图像保存到S3,但无法让它们保存。 / p>

model / user.rb

  class User< ApplicationRecord 
#此方法将属性:avatar与文件附件关联
has_attached_file:avatar,styles:{
thumb:'100x100>',
square:'200x200# ',
medium:'300x300>'
}

#验证附加图片是image / jpg,image / png等
validates_attachment_content_type:avatar,:content_type => /\Aimage\/.*\Z/
结束

迁移

 类AddAvatarToUsers< ActiveRecord :: Migration [5.1] 
def self.up
add_attachment:users,:avatar
end
$ b def self.down
remove_attachment:users, :avatar
end
end

controllers / users_controller.rb

  class UsersController< ApplicationController 
def编辑
@user = User.find_by(id:params [:id])
结束
$ b def更新
@user = User。 find(params [:id])

if @ user.update(user_params)
flash [:notice] =编辑成功
redirect_to(/ users /#{ @ user.id})
end
end

private

def user_params
params.require(:user).permit( :avatar,:name,:email,:phone_number,:description,:college_name)
结束
$ b $结束

为什么图像头像没有存储在数据库中?
我应该添加任何数据库列吗?我该怎么办?我很感激任何输入来帮助我解决这个问题。

解决方案

回形针必须配置为使用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.

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

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