2
我相對較新的Rails,並會感謝任何幫助。上傳base64圖像與回形針 - 導軌4
我的網站接受base64格式的簽名圖像,我試圖使用回形針適配器來解碼圖像並將其保存到我的form
模型中作爲:signature
屬性。我使用的建議使用下面的代碼中給出here(和here)建議:
在模型:
class Thing
has_attached_file :image
在控制器:
def create
image = Paperclip.io_adapters.for(params[:thumbnail_data])
image.original_filename = "something.gif"
Thing.create!(image: image)
...
end
我的假設是,Thing.create!
被設置將Paperclip的模型屬性:image
的值設爲image
變量的值,同時創建並保存新的Thing對象。我想實現我的FormsController
(create動作)之前@form.save
相同的代碼,但我收到此錯誤:
undefined method `before_image_post_process' for #<Class:0x007f94a2a26de8>
我FormsController
:
class FormsController < ApplicationController
before_action :logged_in_user
before_action :admin_user, only: :destroy
def index
@forms = Form.all #paginate
end
def show
@form = Form.find(params[:id])
end
def new
@form = Form.new
end
def create
@form = Form.new(form_params)
# Paperclip adaptor
signature = Paperclip.io_adapters.for(params[:base64])
signature.original_filename = "something.png"
# Attempt to submit image through Paperclip
@form.signature = signature
if @form.save
flash[:success] = "The form has been successfully created!"
redirect_to @form
else
render 'new'
end
end
def edit
@form = Form.find(params[:id])
end
def update
@form = Form.find(params[:id])
if @form.update_attributes(form_params)
flash[:success] = "Form has been updated!"
redirect_to @form
else
render 'edit'
end
end
def destroy
Form.find(params[:id]).destroy
flash[:success] = "Form deleted"
redirect_to forms_path
end
private
def form_params
params.require(:form).permit(:first_name, :last_name, :email, :phone, :address, :member_type, :base64)
end
end
這是我Form
型號:
class Form < ActiveRecord::Base
has_attached_file :signature
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
非常感謝!我很高興我沒有完全離開。 –
現在我正在使用'$(「#base64」).val(base64);'爲':base64'表單屬性賦值。有沒有更有效的方法來做到這一點? –
好吧,如果你使用標準的Rails表單助手,那麼這個元素的id不會是'base64',它會是'form_base64',所以我不確定這是如何工作的,但如果你有這個工作不知何故,這完全沒有問題 - 效率明智。 – smathy