やりたいこと
DBに画像のファイル名を保存して、画像ファイル自体はpublic/user_imageに保存したいです。
ファイル名は"2.jpg"のように、userなどのidに変更して保存したいです。
はまっているところ
フォームからfile_fieldで画像を送信すると、publicに画像が保存されず、DBには#ActionDispatch::Http::UploadedFile:0x007ff8fb722328のようなものが保存されてしまっています。
バージョン
ruby 2.4.1
rails 5.1.4
devise 4.3.0
該当コード
users/registrations_controller.rb
lang
1class Users::RegistrationsController < Devise::RegistrationsController 2 before_action :configure_sign_up_params, only: [:create] 3 before_action :configure_account_update_params, only: [:update] 4 5 def create 6 super do 7 if params[:image] 8 resource.image = "#{resource.id}.jpg" 9 image_file = params[:image] 10 File.binwrite("public/user_images/#{resource.image}", image.read) 11 end 12 13 if resource.save 14 flash[:notice] = "ユーザー登録しました" 15 else 16 flash[:notice] = "ユーザー登録に失敗しました" 17 end 18 end 19 end 20 21 def update 22 super do 23 if params[:image] 24 resource.image = "#{resource.id}.jpg" 25 image_file = params[:image] 26 File.binwrite("public/user_images/#{resource.image}", image.read) 27 end 28 29 if resource.save 30 flash[:notice] = "ユーザー登録しました" 31 else 32 flash[:notice] = "ユーザー登録に失敗しました" 33 end 34 end 35 end 36 37 protected 38 39 # If you have extra params to permit, append them to the sanitizer. 40 def configure_sign_up_params 41 devise_parameter_sanitizer.permit(:sign_up, keys: [:email, :name, :address, :description, :experience, :image]) 42 end 43 44 # If you have extra params to permit, append them to the sanitizer. 45 def configure_account_update_params 46 devise_parameter_sanitizer.permit(:account_update, keys: [:name, :address, :description, :experience, :image]) 47 end 48 49end
deviseを使用していないコントローラーの場合は上手くいくので、deviseのオーバーライドの仕方に問題があるのかもしれません。
paperclipなどの画像アップロードに関するgemは使用しない方針で開発していますので、よろしくお願いしますm(_ _)m
あなたの回答
tips
プレビュー