2017-08-10 62 views
0

我使用下面的寶石:回形針不保存在數據庫

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

我想將圖像保存到S3,但我無法讓他們保存。

模型/ 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 

控制器/ 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("https://stackoverflow.com/users/#{@user.id}") 
    end 
    end 

    private 

    def user_params 
    params.require(:user).permit(:avatar, :name, :email, :phone_number, :description, :college_name) 
    end 

end 

爲什麼圖像頭像沒有存儲在數據庫中? 我應該添加任何數據庫列嗎?我該怎麼辦?我將不勝感激任何意見來幫助我解決這個問題。

+0

嘗試更新用戶時是否收到任何特定的錯誤消息? – michaeldever

+0

不,我不是。沒有錯誤消息。 –

回答

0

回形針必須配置爲使用S3來存儲對象(圖像)。它將在數據庫中存儲與這些元數據相關的元數據,但不包括圖像。

Paperclip Documentation

您還需要設置一個訪問策略爲您的S3存儲桶,並在用戶模型中定義它們是如何從S3解決。

+1

謝謝,爲我解答! –

+1

我已經在config/application.yml中設置了我的S3存儲桶,但是我沒有在用戶模型上定義,因爲我不知道如何在用戶模型上編寫定義。我該怎麼做 –

+0

Paperclip Gem文檔是要走的路。如果你看看S3的具體文檔,它提供了一個操作方法和示例:[Paperclip S3 Documentation](http://www.rubydoc.info/gems/paperclip/Paperclip/Storage/S3) – michaeldever