I was wondering how to implement an image upload using ruby on rails v3? What I got so far is the image is uploaded to my public/uploads directory but in the database the hashed value from the form is stored.
EX of hashed value:
!ruby/object:ActionDispatch::Http::UploadedFile
content_type: image/jpeg
headers: |
Content-Disposition: form-data; name="farmer[picture]"; filename="picture.JPG"
Content-Type: image/jpeg
original_filename: picture.JPG
tempfile: !ruby/object:File {}
Controller:
def new
@farmer = Farmer.new
end
def create
@farmer = Farmer.new(params[:farmer])
if @farmer.save
uploaded_io = params[:farmer][:picture]
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file|
file.write(uploaded_io.read)
end
flash[:success] = "#{@farmer.firstName} #{@farmer.lastName} added"
redirect_to @farmer
else
redirect_to new_path
end
end
Model: empty
View:
<%= form_for(@farmer, :html => { :multipart => true }) do |f| %>
<div class="field">
<%= f.label :picture, "Picture" %>
<%= f.file_field :picture %>
</div>
<div class="actions">
<%= f.submit "Post"%>
</div>
<% end %>开发者_如何学C
So what I would like help with is how to store uploads/image.JPG into the database not the hashed value?
Try not to invent bicycle , paperclip gem is what you are looking for, you may found also alternatives at: ruby toolbox
Cheers
Carrierwave is the best for your problem. If you are using peperclip, you may try to replace with carrierwave. if you have any problem, let me know
精彩评论