0

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 %>

So what I would like help with is how to store uploads/image.JPG into the database not the hashed value?

2 Answers 2

3

Try not to invent bicycle , paperclip gem is what you are looking for, you may found also alternatives at: ruby toolbox

Cheers

Sign up to request clarification or add additional context in comments.

1 Comment

Hmmm... this looks interesting. Do you have an example or quick tutorial on how use paperclip?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.